//
//  HomeTwoViewController.m
//  Light
//
//  Created by 骁唐 on 15/8/26.
//  Copyright (c) 2015年 骁唐. All rights reserved.
#import "HomeTwoViewController.h"
#import "SliderViewController.h"
#import "CalendarViewController.h"
#import "RMDownloadIndicator.h"
#import "constantDefinition.h"
#import "AppDelegate.h"
#import "UserConfig.h"
#import "assessment.h"
#import "ReportViewController.h"
#import "UMSocial.h"
#import "AFNetworking.h"
#import "NetworkTool.h"
#import "CalendarViewController.h"
#import "LoginViewController.h"
#import "BluetoothController.h"
#import "SDProgressView.h"
#import "ConnectViewController.h"

//50S 之后进行固件版本的判断
#define CHANGETIME 30
//固件升级测试
#define TESTOLDHARDNMBER @"1.0"//测试用的固件版本 TODO:上线解开
#define TESTUP 0 //如果是1，则说明是测试固件升级  如果是0 ，这表明是上线版本
static NSInteger numberAll;//更新固件 数据数据部分，数据包的个数。
static NSInteger indexStart;//更新固件 数据部分当前上传到的位置,记住第一帧数据是文件信息，第二帧开始才是数据，随意最后indexStart的数值，=numberAll+1。
//用来判断发送数据的标记
static NSInteger indexNow;//更新固件 标记此次操作之前的一步。用来判断是否发送数据。
static NSInteger numberOfEOT;//更新固件 统计EOT发送的次数。每次发送Start数据的时候，需要赋值为0.跟indexStart同时赋值0.
uint16_t PACKET_SIZE ;//更新固件 数据包的个数
static uint16_t blkNumber ;//更新固件 当前的编号

@interface HomeTwoViewController ()<MBProgressHUDDelegate,UIAlertViewDelegate,UINavigationControllerDelegate,BTServerDelegate,NSURLSessionDownloadDelegate>
//下载文件 session  固件升级
@property (nonatomic,strong) NSURLSession *session;
//自定义ProgressView的个数 固件升级
@property (nonatomic, strong) NSMutableArray *arrayViews;
//固件升级的遮罩层
@property (nonatomic, strong) UIView * viewUpdateHardWare;
//固件升级提示信息
@property (nonatomic, strong) UILabel * labelUpdateHardWare;
//更新主界面的一个定时器  （更新背景的定时器）
@property (nonatomic,strong) NSTimer *upUIDateTimer;
//更新主界面的一个定时器  （绑定状态  每10S 发送一次key）
@property (nonatomic,strong) NSTimer *timerCheckState;
//检查固件更新的，50S检查一次，如果调用了检查方法就停止
@property (nonatomic, strong) NSTimer * timerCheckUpdateHardWard;
//查看报告 button
@property (weak,nonatomic) IBOutlet UIButton * upButton;
//背景图片
@property (weak, nonatomic) IBOutlet UIImageView *backGround;
//左上角显示图标
@property (weak, nonatomic) IBOutlet UIImageView *redUser;
//蓝牙  中央管理者
@property(nonatomic,strong)CBCentralManager *mgr;
//外设t
@property(nonatomic,strong)CBPeripheral *peripheral;
//写入特征
@property(nonatomic,strong)CBCharacteristic *writeCharacteristic;
//读特征
@property(nonatomic,strong)CBCharacteristic *readCharacteristic;
//有key的写入
@property(nonatomic,strong)NSMutableData *keyData;
//报告大于一条 存储进入判断
@property(assign,nonatomic) BOOL report;
//报告存入本地判断
@property(assign,nonatomic) BOOL writeJudge;
//报告可变数组
@property (strong,nonatomic) NSMutableData *reportData;
//今天是周几
@property (assign,nonatomic) int weekToday;
//日历
@property (weak, nonatomic) IBOutlet UILabel *currentCalendar;
//显示星期
@property (weak, nonatomic) IBOutlet UILabel *currentWeek;
//监测view
@property (weak, nonatomic) IBOutlet UIView *monitorView;
//关闭睡眠button (点击进行睡眠模式关闭) 此button不隐藏，表示已经开启睡眠
@property (weak, nonatomic) IBOutlet UIButton *monitorBtn;
//睡眠得分viewq
@property (weak, nonatomic) IBOutlet UIView *scoresView;
//小憩时间view
@property (weak, nonatomic) IBOutlet UIView *sleepView;
//开启睡眠button
@property (strong, nonatomic) UIButton *sleepBtn;
//闹钟有没有响  1标记响，0标记未响
@property (assign, nonatomic) BOOL alarmtriggered;
//类型  正在监测、关闭监测、小憩时间
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
//时间  圆环最下面显示睡眠开始时间—睡眠结束时间
@property (weak, nonatomic) IBOutlet UILabel *bottomTimeLabel;


/*睡眠报告信息展示，不隐藏的*/
//睡眠小时
@property (weak, nonatomic) IBOutlet UILabel *sleepHourLabel;
//睡眠分钟
@property (weak, nonatomic) IBOutlet UILabel *sleepMinLabel;
//深睡小时
@property (weak, nonatomic) IBOutlet UILabel *deepHourLabel;
//深睡分钟
@property (weak, nonatomic) IBOutlet UILabel *deepMinLabel;
//做梦小时
@property (weak, nonatomic) IBOutlet UILabel *dreamHourLabel;
//做梦分钟
@property (weak, nonatomic) IBOutlet UILabel *dreamMinLabel;


//小憩小时 静态的
@property (weak, nonatomic) IBOutlet UILabel *respiteHourLabel;
//小憩分钟 静态的
@property (weak, nonatomic) IBOutlet UILabel *respiteMinLabel;
//小憩秒钟 静态的
@property (weak, nonatomic) IBOutlet UILabel *respiteSecLabel;

//正在检测小时  动态的
@property (weak, nonatomic) IBOutlet UILabel *mointorHourLabel;
//正在检测分数  动态的
@property (weak, nonatomic) IBOutlet UILabel *monitorMinLabel;
//正在检测秒数  动态的
@property (weak, nonatomic) IBOutlet UILabel *monitorSecLabel;

@property (strong, nonatomic) UILabel *percentLabel;//展示没有用到
//日期用来获取XY
@property (weak, nonatomic) IBOutlet UIView *dateView;
//日历button
@property (weak, nonatomic) IBOutlet UIButton *clendarBtn;

@property (assign, nonatomic) CGFloat downloadedBytes;      //当前加载百分比
@property (assign, nonatomic) CGFloat totalDownloadedBytes; //加载总百分比
@property (assign, nonatomic) CGFloat downloadTime;         //加载时长
@property (assign, nonatomic) CGFloat timerFrequency;       //timer刷新率

//睡眠报告图片
@property (weak, nonatomic) IBOutlet UIImageView *reportImage;
//睡眠报告判断
@property (assign,nonatomic) BOOL judgeReport;
//开始时间
@property (copy,nonatomic) NSString *startTime;
//关闭时间
@property (copy,nonatomic) NSString *endTime;
//点击日历返回日期
@property (strong,nonatomic) NSMutableArray *bArray;
//判断今天有没有唤醒
@property (assign,nonatomic) BOOL weekAuto;
//取出智能唤醒存在本地的时间
@property (copy,nonatomic) NSNumber *AutoTime;
//
@property (assign, nonatomic) NSNumber *setalarmtime;
//全局变量创一次
@property (strong,nonatomic) AppDelegate *homeDelegate;
//判断上次是否有睡眠模式（板子开启睡眠模式后关机）
@property (assign,nonatomic) BOOL judgeLastSleep;
//临时脑电波数组
@property (strong,nonatomic) NSMutableArray *temporaryArray;
//蒙版 用户指导蒙层。
@property (weak, nonatomic) IBOutlet UIView *maskView;
//用户指导的图层，需要根据点击的次数进行改变。总共有5张。
@property (weak,nonatomic) IBOutlet UIImageView * imageViewMaskBg;
//用户指导测试button
@property (nonatomic,strong) UIButton * buttonTest;
//向上滑动手势
@property (nonatomic,strong) UISwipeGestureRecognizer * upSwipeGestureRecognizer;
//蓝牙中心设备
@property (strong,nonatomic)BluetoothController *defaultBTServer;
//蓝牙外设信息
@property (assign, nonatomic)PeriperalInfo * nowperih;
//滤波数据6个，从开始时候取，一直保持6个数据。
@property (nonatomic,strong) NSMutableArray * tempX;
//已经过滤好的数据缓存，6个，初始值为6个0.
@property (nonatomic,strong) NSMutableArray * tempY;
//统计关闭波形结束指令发送的次数。30次之后，需要提示用户重启复位眼罩
@property (nonatomic,assign) NSInteger numberOfOFFData;
//统计时候弹出了提示框  0 标识未弹出，不是0标识已经弹出
@property (nonatomic,assign) NSInteger markShow;
//这是变量window的定义
@property(strong,nonatomic)UIWindow *window;
//开启睡眠模式之后，指导用户关闭睡眠模式的按钮
@property (nonatomic,strong) UIButton * buttonUserOrder;
//本地推送
@property (nonatomic,strong) UIApplication * appLication;
//本地推送push_button
@property (nonatomic, weak) IBOutlet UIButton * button_push;
//本地推送展示view
@property (nonatomic, weak) IBOutlet UIView * view_push;
//本地推送跳转button
@property (nonatomic, weak) IBOutlet UIButton * button_goWeb;
//本地推送close_button
@property (nonatomic, weak) IBOutlet UIButton * button_close;
//本地推送图片URL数组
@property (nonatomic, strong) NSMutableArray * url_push_images;
//本地推送链接URL数组
@property (nonatomic, strong) NSMutableArray * url_push_Webs;
//固件升级，提醒用户重启眼罩提示
@property (nonatomic, strong) UIAlertView * alertViewShouRestart;
//提示下载应用的
@property (nonatomic, strong) UIAlertView * alerDown ;
@end

@implementation HomeTwoViewController
{
    
    NSTimer *timerr;//圆环进度定时器
    NSTimer *myTimerr;//时间定时器
    //    //定时跳转到小憩时间
    //    NSTimer *gotoTimerr;
    //写入时间同步定时器
    NSTimer *writeCurrentTime;
    UIAlertView *startAlert;//启动中弹框
    UIAlertView *endAlert;//睡眠模式关闭中弹框
    UIAlertView * connectingAlert;//正在重新连接弹窗
    NSInteger countLoading;//统计用户指导点击的次数，注意需要初始化为0；
    NSArray * arrayImageMask;//用于存储用户指导的图片名称
    int sec;
    int hour;
    int min;
    long long int currentDateSec;//当前的时间
    
    //APP关闭的时间
    long long int lastTime;
    
    CGFloat upProgress;
    
    int currentScore;//当前分数
    CAShapeLayer *backShape;//背景的圆环
    CAShapeLayer *frontShape;//加载的圆环
    UILabel *numLabel;//内部数字Label
    UIButton *scoreButton;
    NSDate *resignDate;
    
    BOOL judgeDisconnect;//判断脱机
    
    NSString *  kServiceUUID;
}

#pragma mark -
#pragma mark viewDidLoad 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.delegate=self;
    self.appLication = [UIApplication sharedApplication];//初始化本地推送
    lastTime = 0;//初始化
    self.numberOfOFFData = 0;//初始化统计发送关闭波形接收的次数，如果超过20次，就需要提醒用户重启眼罩
    self.markShow = 0;//初始化标识，未弹出提示框
    [self getUpdateVersionDownLoad];//下载txt读取iOS版本的方式
    self.temporaryArray = [[NSMutableArray alloc] init];
    self.alarmtriggered = NO;//设置-----标记

    [self backGroundUpdate];//设置背景
    self.upUIDateTimer = [NSTimer scheduledTimerWithTimeInterval:1800 target:self selector:@selector(backGroundUpdate) userInfo:nil repeats:YES];//设置一个循环定时器，每隔30分钟，刷新一个背景
    writeCurrentTime = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(writeCurrentTimeFunc) userInfo:nil repeats:YES];//如果同步时间成功之后，需要关闭定时器。
    [writeCurrentTime setFireDate:[NSDate distantFuture]];//先暂停定时器，在需要的时候再开启
    self.bArray = [[NSMutableArray alloc] init];
    //    redBtnTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(redUserTime) userInfo:nil repeats:YES];
    upProgress = 0.0;
    //本类通知，左上角提示图标闪烁//标记貌似没有使用到
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(redUserInfo:) name:@"userHead" object:nil];
    //注册通知，提示解绑之后需要展示提示信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startActionNews) name:@"headRed" object:nil];
    //背景随时间改变通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backGroundUpdate) name:@"homeBackGround" object:nil];
    //报告接收完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endReportInfo:) name:@"endReport" object:nil];
    
    //关闭定时器通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeTimerCheckState) name:TIMER_REMOVER object:nil];
    //开启定时器通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addTimerCheckState) name:@"addTimerCheckStateADD" object:nil];
    //添加通知 进行固件升级
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(configUpdateHardWard) name:@"removeLabelOfAlertDown" object:nil];
    //添加通知 绑定界面进入的固件升级判断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkUpdateHardWare) name:@"checkUpdateConnect" object:nil];
    //添加通知 设置绑定界面 成功之后进入的首页固件升级判断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkUpdateHardWareHome) name:@"checkUpdateConnectHome" object:nil];
    //添加通知  读取硬件信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readInformationOfHardWare) name:@"readInfoOfHardWare" object:nil];
    //添加通知 获取程序即将不活跃
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resignActive) name:@"resignActive" object:nil];
    //添加通知 获取程序苏醒通知  ,需要读取连接设备电量  //becomeActive
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive) name:@"becomeActive" object:nil];
    
    MBProgressHUD *progressView = [[MBProgressHUD alloc]initWithView:self.view];
    progressView.delegate = self;
    progressView.labelText = @"";
    self.mbProgressHud = progressView;//SXW__调试屏蔽
    //获取当前分数
    UserConfig *config = [UserConfig sharingUserConfig];
    currentScore = [[config getSleepScore] intValue];//获取用户当前分数
    //    if ([[config getConnectCool] intValue] == 1)
    //    {//绑定状态，获取bendingkey。
    //        self.keyData = [config getBluetoothKey];//获取key
    //    }
    [self.view addSubview:progressView];//SXW__调试屏蔽
   
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    self.homeDelegate = delegate;

    delegate.fromwhere = @"Home";
    
    self.defaultBTServer = [BluetoothController defaultBTServer];
    self.defaultBTServer.delegate = (id)self;
    delegate.homepageid = (id)self;
    if ([[config getConnectCool] integerValue] != 1)
    {//如果不是绑定状态
//        [self.timerCheckUpdateHardWard setFireDate:[NSDate distantFuture]];//暂停定时器
    }
    else
    {
    }
    
    if (delegate.Bluetooth && [[config getConnectCool] intValue] == 1)
    {//查看链接绑定状态
        [self.redUser stopAnimating];//左AppDelegate *delegate = [[UIApplication sharedApplication] delegate];上角图标停止闪烁
        self.redUser.image = [UIImage imageNamed:@"home - head"];
        [self homeWritePower]; //请求电量
    }
    else
    {
        [self startActionNews];//设置左上角红色显示小图标
    }
    //创建睡眠开始的button
    //    if (SCREEN_HEIGHT > 560)
    //    {//4S以上的屏幕
    self.sleepBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/6, 140, SCREEN_WIDTH - SCREEN_WIDTH/3, 210)];//以前   开启睡眠button
    //    }
    //    else
    //    {//4S屏幕
    //        self.sleepBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/4, 140, 100, 100)];//SXW__修改
    //    }
    [self.sleepBtn addTarget:self action:@selector(sleepClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.sleepBtn];
    //    [self.sleepBtn setBackgroundColor:[UIColor greenColor]];
    self.sleepBtn.hidden = YES;//开启睡眠button 隐藏
    //睡眠报告数组
    self.reportData = [[NSMutableData alloc] init];
    _sleepHourLabel.textColor = APPCOLOUR;
    _sleepMinLabel.textColor = APPCOLOUR;
    _deepHourLabel.textColor = APPCOLOUR;
    _deepMinLabel.textColor = APPCOLOUR;
    _dreamHourLabel.textColor = APPCOLOUR;
    _dreamMinLabel.textColor = APPCOLOUR;
    _respiteHourLabel.textColor = APPCOLOUR;
    _respiteMinLabel.textColor = APPCOLOUR;
    _respiteSecLabel.textColor = APPCOLOUR;
    _mointorHourLabel.textColor = APPCOLOUR;
    _monitorMinLabel.textColor = APPCOLOUR;
    _monitorSecLabel.textColor = APPCOLOUR;
    self.monitorSecLabel.text = @"00";
    self.monitorMinLabel.text = @"00";
    self.mointorHourLabel.text = @"00";
    _sleepHourLabel.text = @"0";
    _sleepMinLabel.text = @"0";
    [self setLocalSleepAndDeepAndDreamTime];//设置展示的时间
    //生成首页圆环
    [self round];//SXW__标记，就是因为圆环生成了，所以不能点击
    
    //    [self scoresInterface];//睡眠得分显示  SXW__ 和上面的 [self round];冲突了。

    
    self.AutoTime = [config getAutoTime];
    self.setalarmtime = [config getStartalarmTime];
    
    if ([[config getAutoXiaoQiTime] intValue] != 0) {
        delegate.xiaoqiTime = [config getAutoXiaoQiTime];
    }
    myTimerr = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(respiteTimer) userInfo:nil repeats:YES];//初始化定时器   计算睡眠时间的。1s设置一次
    [myTimerr setFireDate:[NSDate distantFuture]];//暂停定时器
    //    //加入主循环池中
    //    [[NSRunLoop mainRunLoop]addTimer:myTimerr forMode:NSDefaultRunLoopMode];
    int cool  = [[config getJudgeCool] intValue];//ƒ状态，然后进行不同的界面风格的显示
    switch (cool)
    {
        case 1:
        {//睡眠得分显示 状态一，显示睡眠的分
            [self scoresInterface];//状态1
        }
            break;
        case 2:
        {//睡眠得分，界面1.    切换到状态二  ，这边点击之后，可以进入“正在监测”
            [self scoreBtnAction];
        }
            break;
        case 3:
        {//小憩时间显示
            [self restTimeInterface];
        }
        default:
            break;
    }
    delegate.xiaoqiMark = @"abcde";
    delegate.isAtHeart = NO;//SXW__没有处于心电界面
    NSString *maskCool = [config getFirstLoginCool];
    if ([maskCool intValue] == 1)
    {//如果不是第一次使用。 1标识已经使用。0 标识初次安装。
        self.maskView.hidden = YES;//用户指导图层 隐藏
        //检查用户是不是注册界面进入的
        AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
        if ([delegate.markGo isEqualToString:@"landing"])
        {//如果标记了是从注册界面过来的。
            delegate.markGo = @"00";//标志位清零
            if (delegate.markIsgetHardNumber)
            {//如果绑定界面有读取到固件版本号标志，这边需要检查固件更新
                delegate.markIsgetHardNumber = NO;//更改标记为NO
                [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(checkUpdateHardWare) userInfo:nil repeats:NO];//2S 之后监测是否有固件更新
            }
            else
            {//绑定界面没有读取到固件版本号
                [[NSNotificationCenter defaultCenter] postNotificationName:@"readInfoOfHardWare" object:nil];//发送通知，读取硬件info
            }
        }
        
    }
    else
    {
        self.typeLabel.hidden = YES;//类型标签 隐藏
        self.bottomTimeLabel.hidden = YES;//时间label 隐藏
        self.maskView.hidden = NO;//用户指导图层  打开
        self.sleepBtn.hidden = YES;//开启睡眠button 隐藏
        //创建用户指导button
        self.buttonTest = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [self.buttonTest addTarget:self action:@selector(startLoadBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.buttonTest];
        countLoading = 0;//初始化用户指导点击次数  //,@"maskImageTwo"
        arrayImageMask = @[@"maskImageOne",@"maskImageThree",@"maskImageFour",@"maskImageFive"];//设置用户指导的图片
        self.imageViewMaskBg.image = [UIImage imageNamed:arrayImageMask[0]];//初始化用户指导图片为第一张
        SliderViewController * sled = [SliderViewController sharedSliderController];
        [sled closePanGesttureRec];//禁用首页滑动
    }
    //向上滑动
    //    self.upSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gotoReportView)];
    //    [self.upSwipeGestureRecognizer setDirection:UISwipeGestureRecognizerDirectionUp];
    //    [self.upButton addGestureRecognizer:self.upSwipeGestureRecognizer];
    //    [self.upButton setBackgroundColor:[UIColor redColor]];//测试
    //    [self.view addGestureRecognizer:self.upSwipeGestureRecognizer];
    [self judgeWeekTodayAuto];//判断今天有没有智能唤醒
    if (self.weekAuto == YES)
    {
        UserConfig *config = [UserConfig sharingUserConfig];
        self.AutoTime = [config getAutoTime];
    }
    
    int myScore = [[config getSleepScore] intValue];//获取睡眠得分  4个小时以上才有睡眠得分//改成3个小时
    if (myScore > 0 && ![config getSubmitSleepMark])
    {
        TJJLog(@"SXw__重传条件已经通过");
        [self sleepTimeAndSleepReportAgain];//上次上传失败，这次继续上传睡眠数据
    }
    self.timerCheckState = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(checkConnectState) userInfo:nil repeats:YES];//设置一个循环定时器，每隔10秒，判断绑定状态
    
//    [self createWindowBackButton];//创建uiwindowButton
//    _window.hidden = YES;
    TJJLog(@"进入界面000");
//    currentScore = 3;
    if (currentScore > 0)
    {
        self.button_push.hidden = NO;
        self.view_push.hidden = YES;
//        [self.button_push sendActionsForControlEvents:UIControlEventTouchUpInside];//代码点击
    }
    else
    {//隐藏push展示的界面
        self.button_push.hidden = YES;
        self.view_push.hidden = YES;
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    [self reportImageAnimation];
    TJJLog(@"进入界面");
}

- (void)viewDidAppear:(BOOL)animated
{
    TJJLog(@"进入界面111");
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    TJJLog(@"推出界面");
}

#pragma mark -
#pragma mark 暂停定时器
-(void)removeTimerCheckState
{
//    [self.timerCheckState invalidate];//销毁
    TJJLog(@"TJJLo暂停定时器");
    //暂停定时器
    [self.timerCheckState setFireDate:[NSDate distantFuture]];
}
#pragma mark -
#pragma mark 开启定时器
-(void)addTimerCheckState
{
    TJJLog(@"TJJLo开启定时器");

    //开启定时器
    [self.timerCheckState setFireDate:[NSDate distantPast]];
}

#pragma mark -
#pragma mark 用户指导点击
-(void)startLoadBtn
{
    countLoading++;//点击次数加1
    switch (countLoading)
    {
        case 0:
        case 1:
        case 2:
        case 3:
        {
            self.imageViewMaskBg.image = [UIImage imageNamed:arrayImageMask[countLoading]];
        }
            break;
        default:
        {
            self.buttonTest.hidden = YES;//隐藏用户使用button
            self.maskView.hidden = YES;//隐藏 用户指导遮层
            countLoading = 0;//计数器清零
            //获取当前分数
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setFirstLoginCool:@"1"];//标记已经使用过用户指导。
            SliderViewController * sled = [SliderViewController sharedSliderController];
            [sled openPanGesttureRec];//打开 首页滑动
            
            AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
            if ([delegate.markGo isEqualToString:@"landing"])
            {//如果标记了是从注册界面过来的。
                delegate.markGo = @"00";//标志位清零
                if (delegate.markIsgetHardNumber)
                {//如果绑定界面有读取到固件版本号标志，这边需要检查固件更新
                    delegate.markIsgetHardNumber = NO;//更改标记为NO
                    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(checkUpdateHardWare) userInfo:nil repeats:NO];//2S 之后监测是否有固件更新
                }
                else
                {//绑定界面没有读取到固件版本号
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"readInfoOfHardWare" object:nil];//发送通知，读取硬件info
                }
            }
        }
            break;
    }
}

#pragma mark -
#pragma mark 读取下位机信息函数
- (void)readInformationOfHardWare
{
    [self performSelector:@selector(readHardInfo) withObject:nil afterDelay:0];//延迟读取硬件信息
    [self performSelector:@selector(readSerialNumber) withObject:nil afterDelay:0.5];//延迟读取硬件序列号信息
    [self performSelector:@selector(readBLEHardInfo) withObject:nil afterDelay:1.1];//延迟读取蓝牙适配器版本信息 1.6
}

#pragma mark -
#pragma mark 左上角提示图标开始轮播 红色
- (void)startActionNews
{
    NSArray *myImages = [NSArray arrayWithObjects:
                         [UIImage imageNamed:@"home-red1"],
                         [UIImage imageNamed:@"home-red2"],
                         [UIImage imageNamed:@"home-red3"],
                         [UIImage imageNamed:@"home-red4"],
                         [UIImage imageNamed:@"home-red5"],
                         [UIImage imageNamed:@"home-red6"],
                         nil];
    self.redUser.animationImages = myImages;
    self.redUser.animationDuration = 3;
    self.redUser.animationRepeatCount = 0;
    [self.redUser startAnimating]; //左上角提示开始闪烁
}

#pragma mark -
#pragma mark 左上角提示图标开始轮播 黄色
- (void)startActionNewsPower
{
//    NSArray *myImages = [NSArray arrayWithObjects:
//                         [UIImage imageNamed:@"home-yellow1"],
//                         [UIImage imageNamed:@"home-yellow2"],
//                         [UIImage imageNamed:@"home-yellow3"],
//                         [UIImage imageNamed:@"home-yellow4"],
//                         [UIImage imageNamed:@"home-yellow5"],
//                         [UIImage imageNamed:@"home-yellow6"],
//                         nil];
    NSArray *myImages = [NSArray arrayWithObjects:
                         [UIImage imageNamed:@"home-yellow1"],
                         [UIImage imageNamed:@"home-yellow6"],
                         nil];
    self.redUser.animationImages = myImages;
    self.redUser.animationDuration =2;
    self.redUser.animationRepeatCount = 0;
    [self.redUser startAnimating]; //左上角提示开始闪烁
}

#pragma mark -
#pragma mark 获取进入不活跃的时间,展示没用到
- (void)resignActive
{
    //    //获取进入不活跃的时间
    //    resignDate =
    //    [myTimerr setFireDate:[NSDate distantFuture]];
    //    [myTimerr setFireDate:[NSDate distantFuture]];
    
}

#pragma mark -
#pragma mark 后台启动程序，调用该方法
- (void)becomeActive {
    /*
     SXW__判断绑定状态和连接状态。
     如果是绑定状态、并且处于未连接状态的，需要根据存储的key和UUID信息主动进行连接
     */
    //获取绑定状态
    UserConfig *config = [UserConfig sharingUserConfig];
    NSString *maskCool = [config getFirstLoginCool];
    if ([maskCool intValue] != 1)
    {//如果不是第一次  1标记已经安装过了，0标识第一次使用
        //TODO：不处理
        SliderViewController * sled = [SliderViewController sharedSliderController];
        [sled closePanGesttureRec];//禁用首页滑动
    }
    else
    {
        NSString *cool = [config getConnectCool];
        if ([cool intValue] == 1)
        {//已经绑定设备
            AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
            if (delegate.mgr.selectPeripheral != nil)
            {
                if (delegate.mgr.selectPeripheral.state != CBPeripheralStateConnected)
                {
                    [delegate.mgr reconnect:delegate.mgr.selectPeripheral];
                }
                else if (![config getUpdateHardWare] && !delegate.updating && !delegate.isUpdateHardWare)
                {//如果没有处于升级状态
                    TJJLog(@"绑定了设备，需要其他读取信息操作");
                    [self homeWritePower];//请求电量
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"readInfoOfHardWare" object:nil];//发送通知，读取硬件info
                }
            }
        }
        else
        {//未绑定设备
            TJJALERT_VIEW(@"请在设置中进行设备绑定");
        }
    }
}

#pragma mark -
#pragma mark 打开左侧边栏界面
- (IBAction)useBtnClick {
    SliderViewController *slider = [SliderViewController sharedSliderController];
    [slider showLeftViewController];
}

#pragma mark -
#pragma mark 点击日历
- (IBAction)calendarClick {
    [_mbProgressHud show:YES];//菊花打开
    //传的参数
    UserConfig * config = [UserConfig sharingUserConfig];
    NSDictionary *dic= @{@"Token":[config getToken],@"uploaddate":@"1990-10"};
    __weak HomeTwoViewController *weakSelf = self;
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    httpManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //地址
    [httpManager POST:HOME_DATE_DATA parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [_mbProgressHud hide:YES];//隐藏菊花
        NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];//获取状态码
        NSDictionary *Dic = [NetworkTool parseJSONStringToNSDictionary:retDic[@"b"]];//获取请求数据
        TJJLog(@"日历获取数据：%@",Dic);
        if ([retDic[@"a"] intValue] == 1)
        {
            UIStoryboard *CalendarStoryboard = [UIStoryboard storyboardWithName:@"Calendar" bundle:nil];
            CalendarViewController *calendar = [CalendarStoryboard instantiateViewControllerWithIdentifier:@"UseCalendarID"];
            calendar.bArray = (NSMutableArray *)Dic;
            calendar.uploaddate = retDic[@"uploaddate"];
            [weakSelf presentViewController:calendar animated:YES completion:nil];
        }
        else if ([retDic[@"a"] intValue] == 0)
        {
            UIStoryboard *CalendarStoryboard = [UIStoryboard storyboardWithName:@"Calendar" bundle:nil];
            CalendarViewController *calendar = [CalendarStoryboard instantiateViewControllerWithIdentifier:@"UseCalendarID"];
            [weakSelf presentViewController:calendar animated:YES completion:nil];
        }
        else if([retDic[@"a"] intValue] == -1)
        {
            if (TJJiOS8) {
                UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期,请您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:Alertview animated:YES completion:nil];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    UserConfig *config = [UserConfig sharingUserConfig];
                    [config setHaveLogin:@"lalala"];
                    [config setToken:@"123"];
                    [config setUserHeadData:nil];
                    UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                    LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
                    loginVc.quit = YES;
                    [self.navigationController pushViewController:loginVc animated:YES];
                }];
                [Alertview addAction:action];
            }
            else
            {
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
                alert.tag = 97;
                [alert show];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_mbProgressHud hide:YES];//隐藏菊花
        TJJALERT_VIEW(ERROR_NETWORKINFO);
    }];
}

#pragma mark -
#pragma mark 生成圆环
- (CAShapeLayer *)buidAroundWithLineWidth:(CGFloat)lineWidth fram:(CGRect)framRect fillColor:(CGColorRef)color Start:(CGFloat)strokeStart end:(CGFloat)strokeEnd {
    CAShapeLayer *cashapeLayer = [[CAShapeLayer alloc]init];
    cashapeLayer.strokeColor = color;
    cashapeLayer.lineWidth = lineWidth;
    cashapeLayer.fillColor = [[UIColor clearColor]CGColor];
    cashapeLayer.lineCap = kCALineCapRound;
    CGPoint centerPoint =  CGPointMake(CGRectGetMidX(framRect), CGRectGetMidY(framRect));
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:framRect.size.width/2 startAngle:135 *M_PI/180 endAngle:405*M_PI/180 clockwise:YES];
    cashapeLayer.path = bezierPath.CGPath;
    cashapeLayer.strokeStart = strokeStart;
    cashapeLayer.strokeEnd = strokeEnd;
    return cashapeLayer;
}

#pragma mark -
#pragma mark  生成背景的圆环
- (void)round
{
    if (SCREEN_HEIGHT < 560)
    {//4s屏幕
        int mar = 165;
        //背景的圆环
        backShape = [[CAShapeLayer alloc]init];
        backShape = [self buidAroundWithLineWidth:16 fram:CGRectMake(SCREEN_WIDTH/2- mar*RATIO4S/2+3,self.dateView.frame.origin.y + self.dateView.frame.size.height + 5,mar*RATIO4S,mar*RATIO4S) fillColor:[[UIColor colorWithRed:1 green:1 blue:1 alpha:0.3] CGColor] Start:0.0 end:1.0 ];
        [self.view.layer addSublayer:backShape];
        //加载的圆环
        frontShape = [[CAShapeLayer alloc]init];
        frontShape = [self buidAroundWithLineWidth:16 fram:CGRectMake(SCREEN_WIDTH/2- mar*RATIO4S/2+3,self.dateView.frame.origin.y + self.dateView.frame.size.height + 5,mar*RATIO4S,mar*RATIO4S) fillColor:[COLORWITHRGB(46.0, 237.0, 194.0) CGColor] Start:0.0 end:0.0 ];
        [self.view.layer addSublayer:frontShape];
        //内部数字
        numLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2- mar*RATIO4S/2+3,self.dateView.frame.origin.y + self.dateView.frame.size.height + 5,mar*RATIO4S,mar*RATIO4S)];
        numLabel.textAlignment = NSTextAlignmentCenter;
        numLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:60];
        numLabel.textColor  = [UIColor whiteColor];
        numLabel.adjustsFontSizeToFitWidth = YES;
        numLabel.minimumScaleFactor = 50;
        [self.view addSubview:numLabel];
        numLabel.text = @"0";//内部数字Label 设置为0
    }
    else
    {//背景的圆环  iPhone5\6\6P
        backShape = [[CAShapeLayer alloc]init];
        backShape = [self buidAroundWithLineWidth:20 fram:CGRectMake(SCREEN_WIDTH/2- 240*RATIO/2,self.dateView.frame.origin.y + self.dateView.frame.size.height + 10,240*RATIO,240*RATIO) fillColor:[[UIColor colorWithRed:1 green:1 blue:1 alpha:0.3] CGColor] Start:0.0 end:1.0 ];
        [self.view.layer addSublayer:backShape];
        //加载的圆环
        frontShape = [[CAShapeLayer alloc]init];
        frontShape = [self buidAroundWithLineWidth:20 fram:CGRectMake(SCREEN_WIDTH/2- 240*RATIO/2,self.dateView.frame.origin.y + self.dateView.frame.size.height + 10,240*RATIO,240*RATIO) fillColor:[COLORWITHRGB(46.0, 237.0, 194.0) CGColor] Start:0.0 end:0.0 ];
        [self.view.layer addSublayer:frontShape];
        //内部数字
        numLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2- 240*RATIO/2,self.dateView.frame.origin.y + self.dateView.frame.size.height + 8,240*RATIO,240*RATIO)];
        numLabel.textAlignment = NSTextAlignmentCenter;
        numLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:80];
        numLabel.textColor  = [UIColor whiteColor];
        numLabel.adjustsFontSizeToFitWidth = YES;
        numLabel.minimumScaleFactor = 70;
        [self.view addSubview:numLabel];
        numLabel.text = @"0";//内部数字Label 设置为0
    }
    //点击按钮
    scoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //     scoreButton.backgroundColor = [UIColor redColor];
    [scoreButton setFrame:CGRectMake(SCREEN_WIDTH/2- 240*RATIO/2,self.dateView.frame.origin.y + self.dateView.frame.size.height + 8,240*RATIO,240*RATIO)];
    [scoreButton addTarget:self action:@selector(scoreBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scoreButton];
    
    timerr = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(upprogress) userInfo:self repeats:YES];// 模拟下载进度
}

#pragma mark -
#pragma mark 首页圆环动态进度条
- (void)upprogress {
    if (upProgress < 1.0) {
        upProgress += 0.01;
        // 循环
        if (upProgress  >= currentScore *0.01){
            upProgress = currentScore *0.01;
            [timerr invalidate];//销毁
            
        }
        numLabel.text = [NSString stringWithFormat:@"%.0f",upProgress*100];//内部数字Label  设置内容
        frontShape.strokeEnd = upProgress;
    }
}

#pragma mark -
#pragma mark 状态切换
- (void)scoreBtnAction
{
    //睡眠得分，界面1. 切换到状态二
    AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
    //获取绑定状态
    UserConfig *config = [UserConfig sharingUserConfig];
    NSString *cool = [config getConnectCool];
    NSString *maskCool = [config getFirstLoginCool];
    if ([maskCool intValue] != 1)
    {//如果不是第一次使用，不处理   1标识已经使用过，0标识初次安装使用
    }
    else
    {
        if ([cool intValue] == 1)
        {//已经绑定设备
            if (appdelegate.Bluetooth)
            {//蓝牙已经连接
                if (TJJiOS8)
                {
                    UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"是否打开睡眠模式" message:nil preferredStyle:UIAlertControllerStyleAlert];
                    [self presentViewController:Alertview animated:YES completion:nil];
                    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"打开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                              {
                                                  //开启睡眠模式
                                                  NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_SLEEPSTART];
                                                  if ([appdelegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"])
                                                  {//TODO:crash奔溃
                                                      [appdelegate.peripheral writeValue:data
                                                                       forCharacteristic:appdelegate.writeCharacteristic
                                                                                    type:CBCharacteristicWriteWithResponse];
                                                  }
                                                  
                                                  startAlert = [[UIAlertView alloc] initWithTitle:nil message:@"睡眠模式启动中" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                                                  [startAlert show];
                                                  
                                                  [self performSelector:@selector(startSleepModelFunc) withObject:nil afterDelay:1.5];
                                                  
                                              }];
                    
                    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    }];
                    [Alertview addAction:action1];
                    [Alertview addAction:action2];
                }
                else
                {//iOS8 以下的方法
                    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"是否打开睡眠模式" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    alert.tag = 271;
                    [alert show];
                }
            }
            else
            {//蓝牙已经断开连接，已经脱机正在尝试连接
                judgeDisconnect = YES;
                TJJALERT_VIEW(@"已脱机正在尝试连接");
            }
        }
        else
        {//未绑定设备
            TJJALERT_VIEW(@"请在设置中进行设备绑定");
        }
    }
}

#pragma mark -
#pragma mark 1s后判断睡眠模式是否开启成功
- (void)startSleepModelFunc
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if (delegate.sleepModel == YES)
    {//如果开启睡眠模式
        [startAlert removeFromSuperview];
        [startAlert dismissWithClickedButtonIndex:0 animated:YES];
        [self writeCool];//状态请求
        NSString * locationString=[TJJDefines getTimeTypeOne];//设置开始时间 HH:mm
        UserConfig *config = [UserConfig sharingUserConfig];
        [config setDreamImprove:NO];//设置梦境控制为NO；
        [config setDreamImproveShow:NO];//设置睡眠报告梦境控制标记 NO
        delegate.dreamImprove = NO;//设置梦境控制为NO.
        [config setSleepImprove:NO];//设置睡眠改善为NO;
        [config setSleepImproveShow:NO];//设置睡眠报告睡眠改善标记 NO
        delegate.sleepImprove = NO;//设置睡眠改善为NO
        [config setReportStartTime:locationString];//设置报告开始时间 09:00
        [config setReportStartTimeTypeDate:[TJJDefines getDateTimeTypeOne]];//设置睡眠报告开始时间  NSDate类型的字符串  如：2016-01-07 13:30:37
        [config setSLeepTime:@"0"];//TODO：SXW__初始化睡眠长度
        [config setHadSetEndTime:NO];//初始化结束时间设置标志为NO
        self.startTime = locationString;//设置开始时间 HH:mm
        TJJLog(@"睡眠报告开始时间:%@",locationString);
        AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        long long int date = [TJJDefines getTimeIntSince1970];//获取当前时间的秒数
        delegate.startSleepModelTime = date;//设置开始时间
        NSString *currentTime = [[NSString alloc]initWithFormat:@"%lld",delegate.startSleepModelTime];
        [config setStopwatchTime:currentTime];
        [config setSleepStartTime:self.startTime];
        long long int alarmtime =[[config getAutoTime] integerValue];
        NSArray * splited = [self.startTime componentsSeparatedByString:@":"];
        long long int sleept = (int)[splited[0] integerValue]*3600 + (int)[splited[1] integerValue]*60;
        if (sleept>=alarmtime)
            [config setTodayAlarmClockCarryOutMark:@"1"];
        [self stopWatchInterface];
        //TODO:用户指导
//        if ([config isFirstUseSleep])
//        {//判断是否是第一次打开睡眠模式，如果是第一，则进入蒙层引导
//            self.maskView.hidden = NO;//打开隐藏 用户指导遮层
//            self.imageViewMaskBg.image = [UIImage imageNamed:@"maskImageTwo"];//指定引导关闭遮罩层
//            countLoading = 912;
////            [self createWindowBackButton];//创建windowButton。
//            _window.hidden = NO;
//        }
//        else
//        {//不是第一次打开睡眠模式。不用处理
//        }

    }
    else
    {//睡眠模式开启失败
        [startAlert dismissWithClickedButtonIndex:0 animated:NO];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"失败"
                                                        message:@"睡眠模式启动失败"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark -
#pragma mark 秒表界面
- (void)stopWatchInterface
{
    UserConfig *config = [UserConfig sharingUserConfig];
    //设置恢复之前的数据标记
    [config setJudgeCool:@"2"];//设置状态为2，睡眠模式
    //睡眠模式开启btn 消失
    scoreButton.hidden = YES;//点击按钮 隐藏
    numLabel.hidden = YES; //内部数字Label 隐藏
    _sleepHourLabel.text = @"0";
    _sleepMinLabel.text = @"0";
    _deepHourLabel.text = @"0";
    _deepMinLabel.text = @"0";
    _dreamHourLabel.text = @"0";
    _dreamMinLabel.text = @"0";
    _mointorHourLabel.textColor = APPCOLOUR;
    _monitorMinLabel.textColor = APPCOLOUR;
    _monitorSecLabel.textColor = APPCOLOUR;
    self.scoresView.hidden = YES;//睡眠得分View 隐藏
    backShape.hidden = YES;
    frontShape.hidden = YES;
    self.monitorView.hidden = NO;
    self.monitorBtn.hidden = NO;//关闭睡眠button  不隐藏，处于监控状态
    self.typeLabel.hidden = NO;//类型label显示
    _typeLabel.text = @"正在监测";//SXW__测试标记
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    delegate.sleepScore = 0;//临时分数清零
    [config setsleepShenShuiTime:@"0"];//设置新的深睡梦境时间
    [config setDreamTime:@"0"];
    self.bottomTimeLabel.hidden = NO;
    self.bottomTimeLabel.text = [TJJDefines stringTimeDouble:[config getSleepStartTime]];
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    currentDateSec = time;//当前的秒数
    TJJLog(@"切换出睡眠得分，开启睡眠模式");
    [timerr invalidate];//取消圆环 定时器定时器(永久)
    timerr = nil;//一定需要赋值为nil
    //启动定时器  TODO：用户指导
    [myTimerr setFireDate:[NSDate distantPast]];//启动定时器
}


#pragma mark -
#pragma mark 关闭睡眠模式（关闭监测 关闭跑时界面点击）
- (IBAction)monitorClick
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您确定要关闭睡眠模式！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 272;
    [alert show];
}

#pragma mark -
#pragma mark 关闭睡眠计时  跳转到小憩时间或者分数
- (void)stopWatchToScorollOrNep
{
    UserConfig *config = [UserConfig sharingUserConfig];
    _mointorHourLabel.textColor = [UIColor whiteColor];
    _monitorMinLabel.textColor = [UIColor whiteColor];
    _monitorSecLabel.textColor = [UIColor whiteColor];
    _monitorBtn.hidden = YES;//关闭睡眠button 隐藏
    self.typeLabel.hidden = NO;//类型标签 打开
    _typeLabel.text = @"睡眠得分";//类型标签 设置   //关闭监测
    if (![config getHadSetEndTime])
    {//如果没有保存结束时间
        self.endTime = [TJJDefines getTimeTypeOne];//获取当前的时间作为书面结束的时间  格式：HH:mm
        [config setSleepEndTime:self.endTime];//设置睡眠结束时间
        self.bottomTimeLabel.hidden = NO;//睡眠开始时间—睡眠结束时间 显示
        self.bottomTimeLabel.text = [[NSString alloc] initWithFormat:@"%@-%@",[TJJDefines stringTimeDouble:[config getSleepStartTime]],[TJJDefines stringTimeDouble:self.endTime]];//睡眠开始时间—睡眠结束时间 设置值
    }
    [myTimerr setFireDate:[NSDate distantFuture]];//暂停定时器
    //定时跳转到得分或小憩时间
    [self performSelector:@selector(myScrollTimer) withObject:nil afterDelay:1.5];//1.5 之后，根据状态跳转
    [config setStopwatchTime:@"0"];//app关闭时间清0
    lastTime = 0;
    //关闭智能唤醒 1
    [self performSelector:@selector(closeAutoRouseOne) withObject:nil afterDelay:1];
}


#pragma mark -
#pragma mark 关闭智能唤醒 1
-(void) closeAutoRouseOne
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    //关闭睡眠
    NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_AUTOEND_ONE];
    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [delegate.peripheral writeValue:data
                         forCharacteristic:delegate.writeCharacteristic
                                      type:CBCharacteristicWriteWithResponse];
    }
    [self performSelector:@selector(closeAutoRouseTwo) withObject:nil afterDelay:1];
}

#pragma mark -
#pragma mark 关闭智能唤醒2
-(void)closeAutoRouseTwo
{
    AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
    //关闭睡眠
    NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_AUTOEND_TWO];
    if ([appdelegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [appdelegate.peripheral writeValue:data
                         forCharacteristic:appdelegate.writeCharacteristic
                                      type:CBCharacteristicWriteWithResponse];
    }
}

#pragma mark -
#pragma mark 判断睡眠模式关闭有没有写入成功
-(void)judgeOffSleepModel
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    if (delegate.sleepModel == NO)
    {//如果睡眠模式关闭
        [endAlert dismissWithClickedButtonIndex:0 animated:YES];
        if (delegate.judgeSleepReportLenth == YES)
        {//睡眠报告长度确认
            [self stopWatchToScorollOrNep];//关闭睡眠计时
            delegate.judgeSleepReportLenth = NO;//初始化睡眠报告长度确认 为NO初始化操作
        }
        else
        {
            UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:nil message: @"报告接收不完整，接收失败"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            if (delegate.judgeReport != YES)
            {//没有报告判断
                [alert1 show];
            }
            [self stopWatchToScorollOrNep];//关闭睡眠计时
            [endAlert dismissWithClickedButtonIndex:0 animated:YES];//自动点击提示信息
            delegate.judgeSleepReportLenth = NO;
        }
        UserConfig *config = [UserConfig sharingUserConfig];
        [config setStopwatchTime:@"0"];
        [config setAutoXiaoQiTime:@(0)];
        delegate.xiaoqiTime = @(0);
        if (self.alarmtriggered)
            [config setTodayAlarmClockCarryOutMark:@"1"];
    }
    else
    {
        [endAlert dismissWithClickedButtonIndex:0 animated:YES];
        TJJALERT_VIEW(@"报告接收超时");
    }
}

#pragma mark -
#pragma mark 跳转睡眠得分或小憩时间定时器调用方法
- (void)myScrollTimer
{
    //1睡眠得分界面  2睡眠模式开启（秒表）  3 小憩时间
    UserConfig *config = [UserConfig sharingUserConfig];
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if (delegate.sleepScore == 0)
    {
        [config setJudgeCool:@"3"];//设置为状态3
        //小憩时间显示
        [config setLastHour:_mointorHourLabel.text];
        [config setLastMinute:_monitorMinLabel.text];
        [config setLastSec:_monitorSecLabel.text];
        _respiteHourLabel.text = _mointorHourLabel.text;
        _respiteMinLabel.text = _monitorMinLabel.text;
        _respiteSecLabel.text = _monitorSecLabel.text;
        [self restTimeInterface];
    }
    else
    {
        [config setJudgeCool:@"1"];//设置为状态1
        //分数界面显示
        currentScore = delegate.sleepScore;
        [self scoresInterface];
    }
}

#pragma mark -
#pragma mark 睡眠报告通知
-(void)endReportInfo:(NSNotification *)Not
{
    NSDictionary *dict =[Not userInfo];
    if ([dict[@"reportCool"] isEqualToString:@"NO"])
    {
        AppDelegate *delegate =[[UIApplication sharedApplication]delegate];
        if (delegate.judgeSleepReportLenth == YES)
        {
            [endAlert dismissWithClickedButtonIndex:0 animated:YES];
            [self stopWatchToScorollOrNep];//关闭睡眠计时
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(judgeOffSleepModel) object:nil];//可以取消成功
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"报告接收不完整，接收失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            if (delegate.judgeReport !=YES) {
                [alert show];
            }
            [endAlert dismissWithClickedButtonIndex:0 animated:YES];
            [self stopWatchToScorollOrNep];//关闭睡眠计时
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(judgeOffSleepModel) object:nil];//可以取消成功
        }
    }
    if ([dict[@"judgeReport"] isEqualToString:@"NO"]) {
        [endAlert dismissWithClickedButtonIndex:0 animated:YES];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(judgeOffSleepModel) object:nil];//可以取消成功
        [self stopWatchToScorollOrNep];//关闭睡眠计时
    }
}

#pragma mark -
#pragma mark 开启睡眠模式
- (void)sleepClick {
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    //获取绑定状态
    UserConfig *config = [UserConfig sharingUserConfig];
    NSString *maskCool = [config getFirstLoginCool];
    if ([maskCool intValue] != 1)
    {//如果不是第一次使用，不处理  1标识已经使用过，0标识初次安装使用。
    }
    else
    {
        //判断蓝牙是否开启
        if (NO == delegate.Bluetooth)
        {
            //判断是否有KEY
            UserConfig *userConfig = [UserConfig sharingUserConfig];
            NSMutableData *data =  [userConfig getBluetoothKey];
            self.keyData = data;
            TJJLog(@"写入KEY%@",self.keyData);
            if (nil == data)
            {
                TJJALERT_VIEW(@"请在设置中进行设备绑定");
            }
            else
            {
                TJJALERT_VIEW(@"正在重连眼罩，请稍等！");
            }
        }
        else
        {
            if (TJJiOS8)
            {
                UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"是否打开睡眠模式" message:nil preferredStyle:UIAlertControllerStyleAlert];
                
                [self presentViewController:Alertview animated:YES completion:nil];
                
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"打开" style:
                                          UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                              //开启睡眠
                                              AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
                                              NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_SLEEPSTART];
                                              if ([appdelegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
                                                  [appdelegate.peripheral writeValue:data
                                                                   forCharacteristic:appdelegate.writeCharacteristic
                                                                                type:CBCharacteristicWriteWithResponse];
                                              }
                                              startAlert = [[UIAlertView alloc] initWithTitle:nil message:@"睡眠模式启动中" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                                              [startAlert show];
                                              [self performSelector:@selector(napStartSleepModel) withObject:nil afterDelay:1.5];
                                          }];
                UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                }];
                [Alertview addAction:action1];
                [Alertview addAction:action2];
                TJJLog(@"睡眠点击,开启睡眠模式");
            }
            else
            {
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"是否开启睡眠模式" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"打开", nil];
                alert.tag = 279;
                [alert show];
            }
        }
    }
}

#pragma mark -
#pragma mark 小憩开启睡眠模式判断是否成功
-(void)napStartSleepModel
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if (delegate.sleepModel == YES)
    {
        [startAlert dismissWithClickedButtonIndex:0 animated:YES];
        NSString * locationString=[TJJDefines getTimeTypeOne];//获取当前的时间作为开始时间  格式：HH:mm
        UserConfig * config = [UserConfig sharingUserConfig];
        [config setDreamImprove:NO];//设置梦境控制为NO；
        [config setDreamImproveShow:NO];//设置睡眠报告梦境控制标记 NO
        delegate.dreamImprove = NO;//设置梦境控制为NO.
        [config setSleepImprove:NO];//设置睡眠改善为NO;
        [config setSleepImproveShow:NO];//设置睡眠报告睡眠改善标记 NO
        delegate.sleepImprove = NO;//设置睡眠改善为NO
        [config setReportStartTime:locationString];//设置报告开始时间 09:00
        [config setReportStartTimeTypeDate:[TJJDefines getDateTimeTypeOne]];//设置睡眠报告开始时间  NSDate类型的字符串  如：2016-01-07 13:30:37
        [config setSLeepTime:@"0"];//TODO：SXW__初始化睡眠长度
        [config setHadSetEndTime:NO];//初始化结束时间设置标志为NO
        self.startTime = locationString;//获取当前的时间作为开始时间  格式：HH:mm
        TJJLog(@"小憩开启睡眠模式 睡眠报告开始时间:%@",locationString);
        AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        long long int date = [TJJDefines getTimeIntSince1970];//时间，格式从1970到现在的秒数
                delegate.startSleepModelTime =date;
        NSString *currentTime = [[NSString alloc]initWithFormat:@"%lld",delegate.startSleepModelTime];
        [config setStopwatchTime:currentTime];
        [config setSleepStartTime:self.startTime];
        long long int alarmtime =[[config getAutoTime] integerValue];
        NSArray * splited = [self.startTime componentsSeparatedByString:@":"];
        long long int sleept = (int)[splited[0] integerValue]*3600 + (int)[splited[1] integerValue]*3600;
        if (sleept>=alarmtime)
            [config setTodayAlarmClockCarryOutMark:@"1"];
        [self napToStopWatchInterface];//小憩时间 显示
        [self writeCool];//状态请求
//        //TODO:用户指导
//        if ([config isFirstUseSleep])
//        {//判断是否是第一次打开睡眠模式，如果是第一，则进入蒙层引导
//            self.maskView.hidden = NO;//打开隐藏 用户指导遮层
//            self.imageViewMaskBg.image = [UIImage imageNamed:@"maskImageTwo"];//指定引导关闭遮罩层
//            countLoading = 912;
////            [self createWindowBackButton];//创建windowButton。
//            _window.hidden = NO;
//        }
//        else
//        {//不是第一次打开睡眠模式。不用处理
//        }
    }
    else
    {
        [startAlert dismissWithClickedButtonIndex:0 animated:NO];
        TJJALERT_VIEW(@"睡眠模式启动失败");
    }
}

#pragma mark -
#pragma mark 小憩时间跳转到秒表界面
-(void)napToStopWatchInterface
{
    NSString *  locationString=[TJJDefines getTimeTypeOne];//获取当前的时间，格式：HH:mm
    UserConfig *config = [UserConfig sharingUserConfig];
    [config setReportStartTime:locationString];//设置睡眠报告开始时间 09:00
    [config setReportStartTimeTypeDate:[TJJDefines getDateTimeTypeOne]];//设置睡眠报告开始时间  NSDate类型的字符串  如：2016-01-07 13:30:37
    [config setSLeepTime:@"0"];//TODO：SXW__初始化睡眠长度
    [config setJudgeCool:@"2"];//设置状态为2
    [config setsleepShenShuiTime:@"0"];//设置深睡时间0
    [config setDreamTime:@"0"];//设置做梦时间 0
    //设置睡眠展示数据
    _sleepHourLabel.text = @"0";
    _sleepMinLabel.text = @"0";
    _deepHourLabel.text = @"0";
    _deepMinLabel.text = @"0";
    _dreamHourLabel.text = @"0";
    _dreamMinLabel.text = @"0";
    self.sleepView.hidden = YES;//睡眠View 隐藏
    self.scoresView.hidden = YES;  //睡眠得分View 隐藏
    _monitorBtn.hidden = NO;//关闭睡眠button 打开
    self.sleepBtn.hidden = YES;//开始睡眠button  隐藏
    frontShape.hidden = YES;//加载的圆环 隐藏
    backShape.hidden = YES;//背景圆环 隐藏
    self.bottomTimeLabel.hidden = NO;//开始到结束时间标签 隐藏
    self.typeLabel.hidden = NO;//type标签 打开
    self.monitorView.hidden = NO;//监测View 打开
    _mointorHourLabel.text = @"00";//设置动态时间，初始值
    _monitorMinLabel.text = @"00";
    _monitorSecLabel.text = @"00";
    _mointorHourLabel.textColor = APPCOLOUR;
    _monitorMinLabel.textColor = APPCOLOUR;
    _monitorSecLabel.textColor = APPCOLOUR;
    sec = 0;
    min = 0;
    hour = 0;
    _typeLabel.text = @"正在监测";//SXW__测试标记
    self.startTime = locationString;//睡眠模式开始时间
    self.bottomTimeLabel.text = [TJJDefines stringTimeDouble:self.startTime];
    [config setSleepStartTime:locationString];//设置睡眠开始时间
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    long long int date = [TJJDefines getTimeIntSince1970];
    delegate.startSleepModelTime =date;
    //临时分数清零
    delegate.sleepScore = 0;
    currentDateSec = date;//当前的时间，用来刷新时间显示用的。int类型
    [myTimerr setFireDate:[NSDate distantPast]];//开启定时器
    // [self.sleepBtn removeFromSuperview];
}

#pragma mark -
#pragma mark 正在检测计时器  每隔一秒执行一次
- (void)respiteTimer
{
    if (self.homeDelegate.Bluetooth == NO)
    {//蓝牙断开连接
        if(judgeDisconnect == NO)
        {
            TJJALERT_VIEW(@"已脱机正在尝试连接");
            judgeDisconnect = YES;
        }
    }
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    long long int totaldateSec = (long long int)time;//现在的时间
    while (totaldateSec<=0)
    {
        time = [[NSDate date] timeIntervalSince1970];
        totaldateSec = (long long int)time;//现在的时间
    }
    long long int currentTotalSec;
    if (lastTime != 0 )
    {
        currentTotalSec = lastTime;
    }
    else
    {
        currentTotalSec = currentDateSec;
    }
    long  long  int poorSec = (long long int)(totaldateSec - currentTotalSec);
    while  (poorSec<0)
    {
        time = [[NSDate date] timeIntervalSince1970];
        totaldateSec = (long long int)time;//现在的时间
        poorSec = (long long int)(totaldateSec - currentTotalSec);//将检测时间的秒数传过去
        
    }
    [self updateStopWatchTime:poorSec];//更新时间界面
//    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
//    if (delegate.sleepAutoMark == YES) {
        [self JudgeTimeStop:poorSec];
//    }
}

#pragma mark -
#pragma mark 计时器显示数据
- (void)updateStopWatchTime:(long long int) poorSec
{
    sec = poorSec%3600%60;
    min = poorSec%3600/60;
    hour = (int)poorSec/3600;
    if (sec < 10) {
        [self.monitorSecLabel setText:[NSString stringWithFormat:@"0%d",sec]];
    }else
    {
        [self.monitorSecLabel setText:[NSString stringWithFormat:@"%d",sec]];
    }
    if (min < 10) {
        [self.monitorMinLabel setText:[NSString stringWithFormat:@"0%d",min]];
    }else
    {
        [self.monitorMinLabel setText:[NSString stringWithFormat:@"%d",min]];
    }
    if (hour < 10) {
        [self.mointorHourLabel setText:[NSString stringWithFormat:@"0%d",hour]];
    }else
    {
        [self.mointorHourLabel setText:[NSString stringWithFormat:@"%d",hour]];
    }
}

#pragma mark -
#pragma mark 判断计时器是否停止（智能唤醒小憩时间）
- (void)JudgeTimeStop:(long long int) poorSec
{
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:date];
    int myHour = (int)[comps hour];
    int minute = (int)[comps minute];
    int mysecond = (int)[comps second];
    int  currentsec2_24 = myHour *3600 +minute *60+mysecond;
    NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970];
    while (nowtime<=0)
        nowtime = [[NSDate date] timeIntervalSince1970];
    long long int currentXiaoQiSec = (long long int) nowtime;
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate.xiaoqiTime intValue] != 0) {
        if (currentXiaoQiSec >= [delegate.xiaoqiTime intValue]) {
            [myTimerr setFireDate:[NSDate distantFuture]];//暂停定时器
            UserConfig *config =[UserConfig sharingUserConfig];
            long long int sttime = [[config getStopwatchTime] intValue];
            long long int resume = [delegate.xiaoqiTime integerValue] - sttime;
            [self updateStopWatchTime:resume];
        }
    }
    UserConfig *config = [UserConfig sharingUserConfig];
    NSNumber *settime = [config getStartalarmTime];
    NSString* todayclockdone = [config gettodayAlarmClockCarryOutMark];
    NSNumber* weekmask1 = [config getAlarmMask];
    if (settime!=nil && weekmask1!=nil)
    {
        NSDate * lastdate = [NSDate dateWithTimeIntervalSince1970:[settime doubleValue]];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *comps1 = [[NSDateComponents alloc] init];
        NSInteger unitFlags = NSYearCalendarUnit |
        NSMonthCalendarUnit |
        NSDayCalendarUnit |
        NSWeekdayCalendarUnit |
        NSHourCalendarUnit |
        NSMinuteCalendarUnit |
        NSSecondCalendarUnit;
        comps1 = [calendar components:unitFlags fromDate:lastdate];
        long long int alarmtime =[[config getAutoTime] integerValue];
        NSInteger weekmask = [weekmask1 integerValue];
        NSInteger todayweek = [comps weekday];
        if (todayweek == 1)
            todayweek = 6;
        else todayweek = todayweek -2;
        if ([comps day]!=[comps1 day])
        {
            [config setTodayAlarmClockCarryOutMark:@"0"];
            NSTimeInterval settime = [[NSDate date] timeIntervalSince1970];
            [config setStartalarmTime:@(settime)];
        }
        if ([todayclockdone isEqualToString:@"0"])
        {
            if (currentsec2_24>=alarmtime&&(weekmask&(1<<todayweek))) {
                [myTimerr setFireDate:[NSDate distantFuture]];//暂停定时器
                NSString * startString = [config getSleepStartTime];
                NSArray * splited = [startString componentsSeparatedByString:@":"];
                long long int lastforsecond = [splited[0] integerValue]*3600 + [splited[1] integerValue]*60;
                long long int totaltime = alarmtime-lastforsecond;
                if (totaltime<0)
                    totaltime = totaltime + 24*3600;
                self.alarmtriggered = YES;
                [self updateStopWatchTime:totaltime];
                delegate.judgeAuto = NO;
            }
        }
    }
    //到24小时关闭定时器
    if (hour >= 24)
    {
        [myTimerr setFireDate:[NSDate distantFuture]];//暂停定时器
        [self.monitorSecLabel setText:[NSString stringWithFormat:@"%d%d",0,0]];
        [self.monitorMinLabel setText:[NSString stringWithFormat:@"%d%d",0,0]];
        [self.mointorHourLabel setText:[NSString stringWithFormat:@"%d%d",2,4]];
    }
}

#pragma mark -
#pragma mark 分享点击
- (IBAction)shareClick {
    //传的参数
    UserConfig *config =[UserConfig sharingUserConfig];
    NSDictionary *dic= @{@"Token":[config getToken]};
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc] init];
    httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    //分享数据获取的地址
    [httpManager POST:HOME_SHARE parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
        NSDictionary *Dic = [NetworkTool parseJSONStringToNSDictionary:retDic[@"b"]];
        if ([retDic[@"a"] intValue] == 1) {
            TJJLog(@"获取分享的数据。");
            [UMSocialData defaultData].extConfig.qqData.url = Dic[@"connect"];
            [UMSocialData defaultData].extConfig.wechatSessionData.url = Dic[@"connect"];
            [UMSocialData defaultData].extConfig.sinaData.urlResource.url = Dic[@"connect"];
            TJJLog(@"分享内容：%@",Dic);//连接是连接获取的文字是网络获取的、图片是应用图片。
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:UMKEY
                                              shareText:Dic[@"headline"]
                                             shareImage:[UIImage imageNamed:@"icon.png"]
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToQQ,UMShareToWechatSession,UMShareToWechatTimeline,nil]
                                               delegate:nil];
        }else if ([retDic[@"a"] intValue] == 0) {
            TJJLog(@"0");
        }else if([retDic[@"a"] intValue] == -1){
            TJJLog(@"-11111111");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        TJJLog(@"首界面分享失败！");
    }];
}

#pragma mark -
#pragma mark  睡眠时间 上传接口  本地推送
-(void)sleepTimeAndSleepReport
{//睡眠时间接口 传的参数
    //本地推送
//    UILocalNotification * notification = [[UILocalNotification alloc] init];//创建一个本地通知
//    [notification setFireDate:[NSDate distantPast]];//设置通知触发的时间
//    [notification setSoundName:@"scoreAlter.m4a"];//设置通知声音
//    [notification setAlertLaunchImage:@"icon.png"];//设置通知图片
//    NSDictionary * info = @{URL_SCORE_FORTY_PUSH:@"push",URL_SCORE_FORTY:@"image"};
//    notification.userInfo = info;
//    [self.appLication scheduleLocalNotification:notification];//触发本地推送
    //第二种思路，直接在本页面处理图层，使用动画效果。（不用进行本地推送，因为这边界面都是自定义的，而不是标准的本地推送。因为在前台处理，所以跟本地推送后台服务也没有什么关系，所以这版使用前台页面展示效果处理更加直观）
    //推送效果。
//    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    UserConfig *config = [UserConfig sharingUserConfig];
    int myScore = [[config getSleepScore] intValue];//获取睡眠得分  4个小时以上才有睡眠得分//改成3个小时
    if (myScore > 0)
    {
        if (myScore < 40)
        {//大于0，小于40
            [config setImageURL:URL_SCORE_FORTY];//设置背景图片地址
            [config setPushURL:URL_SCORE_FORTY_PUSH];//设置推送地址
        }
        else if (myScore < 60)
        {//大于等于40，小于60
            [config setImageURL:URL_SCORE_SIXTY];
            [config setPushURL:URL_SCORE_SIXTY_PUSH];//设置推送地址
        }
        else if (myScore < 70)
        {//大于等于60，小于70
            [config setImageURL:URL_SCORE_SEVERTY];
            [config setPushURL:URL_SCORE_SEVERTY_PUSH];//设置推送地址
        }
        else if (myScore < 85)
        {//大于等于70，小于85
            [config setImageURL:URL_SCORE_EIGHTFIVE];
            [config setPushURL:URL_SCORE_EIGHTFIVE_PUSH];//设置推送地址
        }
        else
        {//大于等于85
            [config setImageURL:URL_SCORE_ONEHUNDRED];
            [config setPushURL:URL_SCORE_ONEHUNDRED_PUSH];//设置推送地址
        }
        
        [UIView animateWithDuration:0.2 animations:^{
            self.view_push.hidden = YES;//先隐藏。
            self.button_push.hidden = NO;
            [self.button_push sendActionsForControlEvents:UIControlEventTouchUpInside];//代码驱动点击事件,弹出窗口
        }];//push_button需要展示。
    }

//    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
//    UserConfig *config = [UserConfig sharingUserConfig];
//    myScore = [[config getSleepScore] intValue];//获取睡眠得分  4个小时以上才有睡眠得分//改成3个小时
    if (myScore > 0)
    {//分数大于零   睡眠报告接口
        NSData *reportData = [config getSleep];//获取睡眠报告
        NSMutableString *reportStr = [[NSMutableString alloc] init];
        Byte *testByte = (Byte *)[reportData bytes];
        for(int i=0;i<[reportData length];i++)
        {
            switch (testByte[i])
            {
                case 1:
                    [reportStr appendString:@"1-"];
                    break;
                case 2:
                    [reportStr appendString:@"2-"];
                    break;
                case 3:
                    [reportStr appendString:@"3-"];
                    break;
                case 4:
                    [reportStr appendString:@"4-"];
                    break;
                case 5:
                    [reportStr appendString:@"5-"];
                    break;
                case 6:
                    [reportStr appendString:@"6-"];
                    break;
                default:
                    break;
            }
        }
        TJJLog(@"解析上传准备数据%@",reportStr);
        
        
//        NSDictionary *dicTwo= @{@"Token":[config getToken],@"uploaddate":locationString,@"starttime":[config getReportStartTime],@"endtime":self.endTime,@"sleepimprovement":sleepImproveStr,@"Dreammanipulation":dreamImproveStr,@"wakeuptime":@"0",@"Sleepreport":reportStr,@"upTime":currentTime};
        //拼接上传数据 10个参数
        NSMutableDictionary * dataSend = [[NSMutableDictionary alloc] initWithCapacity:0];
        [dataSend setObject:[config getToken] forKey:@"Token"];//Token
        NSString *  locationString= [TJJDefines getDateTypeOne];
        [dataSend setObject:locationString forKey:@"uploaddate"];// 上传日期 2016-01-07
        
        [dataSend setObject:[config getReportStartTime] forKey:@"starttime"];//开始时间 08:00
        [dataSend setObject:[config getSleepEndTime] forKey:@"endtime"];//结束时间 08:00
        if ([config isSleepImprove])
        {
            [dataSend setObject:@"是" forKey:@"sleepimprovement"];//睡眠改善  是/否
        }
        else
        {
            [dataSend setObject:@"否" forKey:@"sleepimprovement"];//睡眠改善  是/否
        }
        if ([config isDreamImprove])
        {
            [dataSend setObject:@"是" forKey:@"Dreammanipulation"];//梦境控制  是/否
        }
        else
        {
            [dataSend setObject:@"否" forKey:@"Dreammanipulation"];//梦境控制  是/否
        }
        [dataSend setObject:@"0" forKey:@"wakeuptime"];//唤醒时间     单位是分 无唤醒为 0
        [dataSend setObject:reportStr forKey:@"Sleepreport"];//睡眠报告   字符串  用“-”连接
        [dataSend setObject:[NSString stringWithFormat:@"%d",(int)[reportData length]] forKey:@"reporttime"];//报告时长  reporttime
//        NSString *currentTime = [TJJDefines getDateTimeTypeOne];//获取上传时间
//        [dataSend setObject:currentTime forKey:@"upTime"];//报告开始时间 yyyy-MM-dd HH:mm:ss 格式：2016-01-07 13:30:37
        
        NSString *currentTime = [config getReportStartTimeTypeDate];//获取上传时间
        [dataSend setObject:currentTime forKey:@"upTime"];//报告开始时间 yyyy-MM-dd HH:mm:ss 格式：2016-01-07 13:30:37

        
        [config setSubmitSleepData:dataSend];//保存睡眠报告上传数据字典
        
        AFHTTPRequestOperationManager *httpManagerTwo = [AFHTTPRequestOperationManager manager];
        httpManagerTwo.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
        httpManagerTwo.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
        //SXW__睡眠报告上传地址
        TJJLog(@"睡眠报告上传接口");
        [httpManagerTwo POST:HOME_SLEEP_SUBMIT parameters:dataSend success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *retDicTwo = [NetworkTool toNSDictionary:responseObject];
            if ([retDicTwo[@"a"] intValue] == 1)
            {
                TJJLog(@"睡眠报告上传成功");
                [config setSubmitSleepMark:YES];//上传报告成功
            }else if ([retDicTwo[@"a"] intValue] == 0)
            {
                TJJALERT_VIEW(@"睡眠报告上传错误");
                [config setSubmitSleepMark:NO];//上传报告失败
            }else if([retDicTwo[@"a"] intValue] == -1)
            {
                [config setSubmitSleepMark:NO];//上传报告失败
                if (TJJiOS8) {
                    UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期,请您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
                    
                    [self presentViewController:Alertview animated:YES completion:nil];
                    
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                        UserConfig *config = [UserConfig sharingUserConfig];
                        [config setHaveLogin:@"lalala"];
                        [config setToken:@"123"];
                        [config setUserHeadData:nil];
                        
                        UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                        LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
                        loginVc.quit = YES;
                        [self.navigationController pushViewController:loginVc animated:YES];
                    }];
                    
                    [Alertview addAction:action];
                }else{
                    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
                    alert.tag = 97;
                    [alert show];
                }
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error)
        {
            [config setSubmitSleepMark:NO];//上传报告失败
            TJJALERT_VIEW(ERROR_NETWORKINFO);
        }];
        
        //睡眠时间接口
        //        NSDictionary *dic= @{@"Token":[config getToken],@"starttime":currentStarTime,@"endtime":self.endTime,@"grade":[config getSleepScore],@"sleepTime":[config getSleepShenShuiTime],@"DreamTime":[config getDreamTime]};
        NSMutableDictionary * dataSendTime = [[NSMutableDictionary alloc] initWithCapacity:0];
        [dataSendTime setObject:[config getToken] forKey:@"Token"];//Token
        [dataSendTime setObject:[config getSleepScore] forKey:@"grade"];//睡眠得分（睡眠等级）
        [dataSendTime setObject:[config getReportStartTime] forKey:@"starttime"];//开始时间  HH:mm
        [dataSendTime setObject:[config getSleepEndTime] forKey:@"endtime"];//睡眠结束时间
        [dataSendTime setObject:[config getSleepShenShuiTime] forKey:@"sleepTime"];//睡眠时间
        [dataSendTime setObject:[config getDreamTime] forKey:@"DreamTime"];//做梦时间
        
        [config setSubmitSleepDataState:dataSendTime];//保存睡眠报告状态上传数据字典

        AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
        httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
        httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
        //地址
        [httpManager POST:HOME_SLEEP_TIME parameters:dataSendTime success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
            if ([retDic[@"a"] intValue] == 1)
            {
                TJJLog(@"睡眠时间上传成功");
            }else if ([retDic[@"a"] intValue] == 0)
            {
                TJJALERT_VIEW(@"睡眠时间上传错误");
            }
            else if([retDic[@"a"] intValue] == -1)
            {
                if (TJJiOS8)
                {
                    UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期,请您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
                    [self presentViewController:Alertview animated:YES completion:nil];
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        UserConfig *config = [UserConfig sharingUserConfig];
                        [config setHaveLogin:@"lalala"];
                        [config setToken:@"123"];
                        [config setUserHeadData:nil];
                        //TODO:重新登录需要清空绑定设备的相关信息
                        UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                        LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
                        loginVc.quit = YES;
                        [self.navigationController pushViewController:loginVc animated:YES];
                    }];
                    [Alertview addAction:action];
                }
                else
                {
                    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
                    alert.tag = 97;
                    [alert show];
                }
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {//网络错误
            TJJALERT_VIEW(ERROR_NETWORKINFO);
        }];
    }
}

#pragma mark -
#pragma mark  睡眠时间 上传接口 再次上传
-(void)sleepTimeAndSleepReportAgain
{//睡眠时间接口 传的参数（只有在上一次上传失败的时候，再调用这个）
    UserConfig *config = [UserConfig sharingUserConfig];
    NSMutableDictionary * dataSend =  [[NSMutableDictionary alloc] initWithDictionary:[config getSubmitSleepData]];//获得保存睡眠报告上传数据字典
    [dataSend setObject:[config getToken] forKey:@"Token"];//修改：Token
    
    if (dataSend != nil)
    {//如果保存的睡眠报告不是nil，则再次上传
        AFHTTPRequestOperationManager *httpManagerTwo = [AFHTTPRequestOperationManager manager];
        httpManagerTwo.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
        httpManagerTwo.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
        //SXW__睡眠报告上传地址
        TJJLog(@"睡眠报告上传接口");
        [httpManagerTwo POST:HOME_SLEEP_SUBMIT parameters:dataSend success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *retDicTwo = [NetworkTool toNSDictionary:responseObject];
            
            switch ([retDicTwo[@"a"] intValue]) {
                case -1:
                {//登录过期
                    [config setSubmitSleepMark:NO];//上传报告失败
                    if (TJJiOS8)
                    {
                        UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期,请您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
                        [self presentViewController:Alertview animated:YES completion:nil];
                        
                        UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            UserConfig *config = [UserConfig sharingUserConfig];
                            [config setHaveLogin:@"lalala"];
                            [config setToken:@"123"];
                            [config setUserHeadData:nil];
                            UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                            LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
                            loginVc.quit = YES;
                            [self.navigationController pushViewController:loginVc animated:YES];
                        }];
                        [Alertview addAction:action];
                    }
                    else
                    {
                        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
                        alert.tag = 97;
                        [alert show];
                    }
                }
                    break;
                case 0:
                {//上传错误
                    TJJALERT_VIEW(@"睡眠报告上传错误");
                    [config setSubmitSleepMark:NO];//上传报告失败
                }
                    break;
                case 1:
                {//上传成功
                    TJJLog(@"睡眠报告上传成功");
                    [config setSubmitSleepMark:YES];//上传报告成功
                }
                    break;
                default:
                {//其他位置错误
                    TJJALERT_VIEW(@"睡眠报告上传错误");
                    [config setSubmitSleepMark:NO];//上传报告失败
                }
                    break;
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {//网络错误
             [config setSubmitSleepMark:NO];//上传报告失败
             TJJALERT_VIEW(ERROR_NETWORKINFO);
         }];
        
        NSMutableDictionary * dataSendTime =  [[NSMutableDictionary alloc] initWithDictionary:[config getSubmitSleepData]];//得到保存睡眠报告状态上传数据字典
        [dataSend setObject:[config getToken] forKey:@"Token"];//修改：Token
        AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
        httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
        httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
        //地址
        [httpManager POST:HOME_SLEEP_TIME parameters:dataSendTime success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
            if ([retDic[@"a"] intValue] == 1)
            {
                TJJLog(@"睡眠时间上传成功");
            }else if ([retDic[@"a"] intValue] == 0)
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误"
                                                                message:@"睡眠时间上传错误"
                                                               delegate:self
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
            else if([retDic[@"a"] intValue] == -1)
            {
                if (TJJiOS8)
                {
                    UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期,请您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
                    [self presentViewController:Alertview animated:YES completion:nil];
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        UserConfig *config = [UserConfig sharingUserConfig];
                        [config setHaveLogin:@"lalala"];
                        [config setToken:@"123"];
                        [config setUserHeadData:nil];
                        //TODO:重新登录需要清空绑定设备的相关信息
                        UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                        LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
                        loginVc.quit = YES;
                        [self.navigationController pushViewController:loginVc animated:YES];
                    }];
                    [Alertview addAction:action];
                }
                else
                {
                    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
                    alert.tag = 97;
                    [alert show];
                }
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            TJJLog(@"网络链接失败 ");
            TJJALERT_VIEW(ERROR_NETWORKINFO);
        }];
    }
}

#pragma mark -
#pragma mark 更新睡眠时间深睡时  做梦时间的展示
-(void)setLocalSleepAndDeepAndDreamTime
{
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    delegate.sleepModel = NO;//添加标记  睡眠接收完成。
    
    dispatch_async(dispatch_get_main_queue(), ^{//主线程  刷新UI
        //得到设置睡眠时间
        UserConfig *config = [UserConfig sharingUserConfig];
        NSString * sleepTime = [config getSleepTime];
        self.bottomTimeLabel.text = [[NSString alloc] initWithFormat:@"%@-%@",[TJJDefines stringTimeDouble:[config getSleepStartTime]],[TJJDefines stringTimeDouble:[config getSleepEndTime]]];//睡眠开始时间—睡眠结束时间 设置值
        if([TJJDefines isNull:sleepTime])
        {
            self.sleepHourLabel.text = @"0";
            self.sleepMinLabel.text = @"0";
        }
        else
        {
            //根据睡眠报告长度设置的，所以这边需要处理。1个长度代表0.5分钟
            int sleepHour = [sleepTime intValue]/120;
            self.sleepHourLabel.text =[[NSString alloc] initWithFormat:@"%d",sleepHour];
            int sleepMin = [sleepTime intValue]%120/2;
            self.sleepMinLabel.text = [[NSString alloc] initWithFormat:@"%d",sleepMin];
        }
        TJJLog(@"-----------------睡%@",sleepTime);
        //得到设置深睡
        NSString *ShenShui =  [config getSleepShenShuiTime];
        if (ShenShui.length <1)
        {
            self.deepHourLabel.text = @"0";
            self.deepMinLabel.text = @"0";
        }
        else
        {
            int deepHour = [ShenShui intValue]/60;
            self.deepHourLabel.text =[[NSString alloc] initWithFormat:@"%d",deepHour];
            int deepMin = [ShenShui intValue]%60;
            self.deepMinLabel.text = [[NSString alloc] initWithFormat:@"%d",deepMin];
        }
        //得到设置做梦
        NSString *DreamTime =  [config getDreamTime];
        if (DreamTime.length <1)
        {
            self.dreamHourLabel.text = @"0";
            self.dreamMinLabel.text = @"0";
        }
        else
        {
            int dreamHour = [DreamTime intValue]/60;
            self.dreamHourLabel.text =[[NSString alloc] initWithFormat:@"%d",dreamHour];
            int dreamMin = [DreamTime intValue]%60;
            self.dreamMinLabel.text = [[NSString alloc] initWithFormat:@"%d",dreamMin];
        }
    });
}

#pragma mark -
#pragma mark 发现蓝牙外设
-(void)didFoundPeripheral
{
    UserConfig *config = [UserConfig sharingUserConfig];
    NSString *currentUUID = [config getBluetoothAddress];
    //AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    int peri_counts = (int)self.defaultBTServer.discoveredPeripherals.count;
    self.nowperih = self.defaultBTServer.discoveredPeripherals[peri_counts-1];
    self.defaultBTServer.selectPeripheral = self.defaultBTServer.discoveredPeripherals[peri_counts-1];
    TJJLog(@"找到设备UUID为：%@",self.nowperih.uuid);
    if ([self.nowperih.uuid isEqualToString:currentUUID])
    {//根据绑定的设备的UUID进行判断
        TJJLog(@"已保存设备的UUID为：%@",self.nowperih.uuid);
        [self.defaultBTServer stopScan:YES];//停止扫描
        [self.defaultBTServer connect:self.nowperih];//连接外设
//        BOOL isSendNokey = [config getMarkNewNoSendKey];
//        if (isSendNokey)
//        {//如果版本号大于1.4 发送key之后，可以不用管是否接收成功，直接进行各种状态改变
////            [self didSuccessState];//执行状态
//            AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
//            delegate.Bluetooth = YES;//蓝牙绑定成功
//            [self performSelector:@selector(didSuccessState) withObject:nil afterDelay:5];
//            TJJLog(@"21212发送nokey");
//        }
//        else
//        {
//            TJJLog(@"212121发送key");
//            [self performSelectorInBackground:@selector(sendkeydata) withObject:nil];//发送key
//        }
    }else
    {
        TJJLog(@"不是绑定的UUID设备");
    }
    return ;
}

#pragma mark -
#pragma mark 发现特征值
-(void)didDiscoverCharacteristic
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.peripheral = self.defaultBTServer.selectPeripheral;
    delegate.writeCharacteristic = self.defaultBTServer.txCharacteristic;
    delegate.readCharacteristic = self.defaultBTServer.rxCharacteristic;
    UserConfig *config = [UserConfig sharingUserConfig];
    self.keyData = [config getBluetoothKey]; //SXW__获取本地key;
    TJJLog(@"获取本地KEY%@",self.keyData);
//需要隔1S发送一次，知道返回07或者06. 统计10次，如果还没有响应的话，需要提示用户：眼罩未响应，尝试重启眼罩。
    //TODO:crash崩溃
//    if (self.keyData != nil && delegate.writeCharacteristic!=nil && [delegate.writeCharacteristic.UUID.UUIDString isEqualToString:@"FFF2"])
//    {
//        [delegate.peripheral writeValue:self.keyData
//                  forCharacteristic:delegate.writeCharacteristic
//                               type:CBCharacteristicWriteWithResponse];
//    }
//    [self sendkeydata];//发送key
    BOOL isSendNokey = [config getMarkNewNoSendKey];
    if (isSendNokey)
    {//如果版本号大于1.4 发送key之后，可以不用管是否接收成功，直接进行各种状态改变
        //            [self didSuccessState];//执行状态
        AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
        delegate.Bluetooth = YES;//蓝牙绑定成功
//        [self performSelector:@selector(didSuccessState) withObject:nil afterDelay:5];
        [self didSuccessState];//成功状态
        TJJLog(@"21212发送nokey");
    }
    else
    {
        TJJLog(@"212121发送key");
        [self performSelectorInBackground:@selector(sendkeydata) withObject:nil];//发送key
    }

    
}

#pragma mark -
#pragma mark 中断连接协议
-(void)didDisconnectFromPeriph
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    if (delegate.updating)
    {//如果是固件升级，就直接弹出提示，并且弹出提示框
        if (_alertViewShouRestart != nil)
        {//先处理掉之前的弹窗
            [_alertViewShouRestart dismissWithClickedButtonIndex:0 animated:YES];
            _alertViewShouRestart = nil;
        }
        if (self.alerDown != nil)
        {//先处理掉之前的弹窗
            [self.alerDown  dismissWithClickedButtonIndex:1 animated:YES];
            self.alerDown = nil;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"眼罩断开连接，请从绑定界面开始重连绑定进行升级！63" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            _alertViewShouRestart.tag = 906;
            [_alertViewShouRestart show];
        });
        return;
    }
    if (delegate.Bluetooth)
    {//设备标记是连接的
    
        delegate.Bluetooth = NO;//标记设备连接状态为NO。
        TJJLog(@"home尝试重连中");
        [self.redUser startAnimating]; //左上角提示开始闪烁
        [dict setObject:@"NO" forKey:@"disConnect"];//连接状态修改为NO，
        //发送电量改变的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];//通知，改变电量显示方案
        NSLog(@"Home 重连标记333-");
        if (delegate.myRemoveConnect != YES)
        {//不是自己手动断开的，其他因素断开的连接de
            // 3.连接外围设备
            [self.defaultBTServer reconnect:self.defaultBTServer.selectPeripheral];
            NSLog(@"Home 重连标记1-%@=",self.defaultBTServer.selectPeripheral);
        }
    }
    else //还在寻找已绑定设备的时候
    {
        NSLog(@"Home 重连标记2-");

        UserConfig *config = [UserConfig sharingUserConfig];
        NSString *connectcool = [config getConnectCool];
        NSString *btaddr = [config getBluetoothAddress];
        
        if ([connectcool isEqualToString:@"1"] && [self.nowperih.uuid isEqualToString:btaddr])
        {//绑定状态，并且uuid等于存储的。
            [self ReconnectDelay];//直接连接设备
            TJJLog(@"解除绑定之前，发现设备会一直去连接，直到连上为止"); //在绑定设备界面断开连接，不需要重连
        }
    }
    return ;
}

#pragma mark -
#pragma mark 检查连接状态
-(void)checkConnectState
{
    if (self.defaultBTServer.selectPeripheral!=nil && self.defaultBTServer.selectPeripheral.state == CBPeripheralStateConnected)
    {
        AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
        if (!delegate.Bluetooth)
        {//如果还是处于连接，但是未处于绑定状态
            UserConfig * config = [UserConfig sharingUserConfig];
            BOOL isSendNokey = [config getMarkNewNoSendKey];
            if (isSendNokey)
            {//如果版本号大于1.4 发送key之后，可以不用管是否接收成功，直接进行各种状态改变
                [self didSuccessState];//执行状态
            }
            else
            {
                [self performSelectorInBackground:@selector(sendkeydata) withObject:nil];//发送key
            }
        }
    }
}

#pragma mark -
#pragma mark 发送key
-(void)sendkeydata
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    while (!delegate.Bluetooth)
    {
        UserConfig *userConfig = [UserConfig sharingUserConfig];
        self.keyData = [userConfig getBluetoothKey]; //SXW__获取本地key;
        if (self.keyData != nil && delegate.writeCharacteristic!=nil && [delegate.writeCharacteristic.UUID.UUIDString isEqualToString:@"FFF2"]) {
            [delegate.peripheral writeValue:self.keyData
                          forCharacteristic:delegate.writeCharacteristic
                                       type:CBCharacteristicWriteWithResponse];
            [NSThread sleepForTimeInterval:0.5];//线程睡眠0.5秒钟
            if ([userConfig getMarkNewNoSendKey])
            {//如果版本大于1.4
                break;
            }
        }
    }
}

#pragma mark -
#pragma mark 重连接外设
-(void)ReconnectDelay //蓝牙断开连接的时候，等会再重连
{
//    [self.defaultBTServer connect:self.nowperih];
//    [self.defaultBTServer connect:self.defaultBTServer.selectPeripheral];
    [self.defaultBTServer reconnect:self.defaultBTServer.selectPeripheral];
}

#pragma mark -
#pragma mark 关闭扫描外设
-(void)didStopScan
{
    
    UserConfig *config = [UserConfig sharingUserConfig];
    NSString *binded = [config getConnectCool];
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if (!delegate.updating && ![config getUpdateHardWare] && !delegate.isUpdateHardWare)
    {//如果没有固件升级，需要发送扫描指令
        if ((!delegate.Bluetooth) && ([binded isEqualToString:@"1"]))
            [self.defaultBTServer startScan];//调用服务方法中的开始搜索方法
    }
    else
    {//如果处于固件升级状态  疑惑  TODO：固件升级
        if ((!delegate.Bluetooth) && ([binded isEqualToString:@"1"]))
        {
            [self.defaultBTServer startScan];//调用服务方法中的开始搜索方法
        }
    }
}

#pragma mark -
#pragma mark 返回的指令接收
- (void)didReadvalue
{//此处监听方法
    //用作报告判断真头data
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSData * incomedate = [delegate.readCharacteristic value];
    Byte * data2byte = (Byte *)[incomedate bytes];
    UserConfig * config = [UserConfig sharingUserConfig];
    
    if (self.mutableData.length > 100 && ([config getUpdateHardWare] || delegate.updating))
    {//下载了最新的固件升级包，并且点击了升级的标识
        if (_alertViewShouRestart != nil) {
            return ;
        }
        const uint8_t * dat = delegate.readCharacteristic.value.bytes;
        NSMutableString * mutableString = [[NSMutableString alloc] initWithCapacity:0];
        for (int i = 0; i < delegate.readCharacteristic.value.length; i++)
        {
            [mutableString appendString:[NSString stringWithFormat:@"%02x",dat[i]]];
        }
        //需要先转成string，之前demo都是判断以string的形式判断的。
        NSString * string = mutableString;
        //TODO:固件升级
//        if ([string isEqualToString:@"43"])//C
//        if ([string containsString:@"43"])//C
        static int numberOfC = 0;
        if ([string containsString:@"43"])//C
        {
            if ([string containsString:@"06"])
            {//ACK 06  传下一帧数据、或者传ETO
                if (indexStart - indexNow == 1 && indexNow < numberAll)
                {
                    NSLog(@"06----传下一帧数据，当前是%lu个数据包",indexNow);
                    //继续传下一帧数据
                    NSRange range = NSMakeRange(indexNow*PACKET_SIZE, PACKET_SIZE);
                    [self WriteDataWithRange:range];//传range
                }
                else if (indexNow == numberAll)
                {
                    if (numberOfEOT == 0)
                    {
                        NSLog(@"06----需要第一次传EOT，总共数据包个数：%lu",numberAll);
                        //发送指令 04
                        AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
                        NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:@"04"];
                        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"])
                        {
                            [delegate.peripheral writeValue:data
                                          forCharacteristic:delegate.writeCharacteristic
                                                       type:CBCharacteristicWriteWithResponse];
                        }
                        numberOfEOT++;
                    }
                    else
                    {
                        TJJLog(@"发送结束指令");
                        [self WriteDateWithEnd];
                    }
                }
                else
                {
                    NSLog(@"06----错误indexStart - indexNow != 1,indexStart=%lu,,,indexNow = %lu",indexStart,indexNow);
                    if (_alertViewShouRestart == nil)
                    {
                        _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"升级故障，请重启眼罩，并从绑定界面开始重连绑定进行升级！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                        _alertViewShouRestart.tag = 906;
                        [_alertViewShouRestart show];
                    }
                }
            }
            else
            {//全部是4343的（包括单个43）
                if (indexNow == indexStart)
                {
                    //如果数据初始化，需要发送第一帧数据
                    NSLog(@"43----传送送开始数据包");
                    indexStart = 0;
                    indexNow = 0;
                    numberOfEOT = 0;
                    blkNumber = 0;//编码号
                    [self WriteDateWithStart];
                }
                else if ((indexStart - indexNow) == 1)
                {//传数据、或者传结束数据帧。
                    if (indexNow == numberAll && numberOfEOT > 0)//需要加一个标记变量。
                    {//如果数据相等，就说明已经传完了。
                        NSLog(@"43----传 结束数据包，总共数据包个数：%d",numberAll);
                        [self WriteDateWithEnd];
                    }
                    else
                    {//不是结束的
                        numberOfC++;//统计接收到43 的个数
                        if (numberOfC > 4)
                        {
                            if (_alertViewShouRestart == nil)
                            {
                                _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"升级故障，请重启眼罩，并从绑定界面开始重连绑定进行升级！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                                _alertViewShouRestart.tag = 906;
                                [_alertViewShouRestart show];
                            }
                        }
                        else
                        {//个数小于4
                            if (indexNow == 0)
                            {
                                NSLog(@"43----传送送开始数据包");
                                indexStart = 0;
                                indexNow = 0;
                                numberOfEOT = 0;
                                blkNumber = 0;//编码号
                                [self WriteDateWithStart];
                            }
                            else
                            {//传数据
                                NSLog(@"43----等待等待-要传上一帧数据包，当前是%lu个数据包,indexStart=%lu,blkNumber=%d",indexNow--,indexStart--,blkNumber--);
                                NSRange range = NSMakeRange(indexNow*PACKET_SIZE, PACKET_SIZE);
                                [self WriteDataWithRange:range];//传range  传上一包数据
                            }
                        }
                    }
                }
                else
                {//43 不会出现这个
                    NSLog(@"4343----不处理不处理");
                }
            }
        }
        else if ([string containsString:@"06"])
        {//ACK 06  传下一帧数据、或者传ETO
            if (indexStart - indexNow == 1 && indexNow < numberAll)
            {
                NSLog(@"06----传下一帧数据，当前是%lu个数据包",indexNow);
                //继续传下一帧数据
                NSRange range = NSMakeRange(indexNow*PACKET_SIZE, PACKET_SIZE);
                [self WriteDataWithRange:range];//传range
            }
            else if (indexNow == numberAll)
            {
                if (numberOfEOT == 0)
                {
                    NSLog(@"06----需要第一次传EOT，总共数据包个数：%lu",numberAll);
                    //发送指令 04
                    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
                    NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:@"04"];
                    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"])
                    {
                        [delegate.peripheral writeValue:data
                                      forCharacteristic:delegate.writeCharacteristic
                                                   type:CBCharacteristicWriteWithResponse];
                    }
                    numberOfEOT++;
                }
                else
                {
                    [self WriteDateWithEnd];
                }
            }
            else
            {
                NSLog(@"06----错误indexStart - indexNow != 1,indexStart=%lu,,,indexNow = %lu",indexStart,indexNow);
                if (_alertViewShouRestart == nil)
                {
                    _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"升级故障，请重启眼罩，并从绑定界面开始重连绑定进行升级！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    _alertViewShouRestart.tag = 906;
                    [_alertViewShouRestart show];
                }
            }
        }
        else if ([string containsString:@"15"])
        {//NAK --0x15
            if (indexNow == numberAll  && numberOfEOT == 1)
            {
                //需要再次传    EOT
                NSLog(@"15----需要第二次传EOT");
                //发送指令 04
                AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
                NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:@"04"];
                if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
                    [delegate.peripheral writeValue:data
                                  forCharacteristic:delegate.writeCharacteristic
                                               type:CBCharacteristicWriteWithResponse];
                }
                numberOfEOT++;
            }
            else
            {//需要将之前的数据包再传一次
//                NSLog(@"15----要传上一帧数据，当前是%lu个数据包,indexStart=%lu,blkNumber=%d",indexNow--,indexStart--,blkNumber--);
//                NSLog(@"15----传%lu个数据包",indexNow);
//                //继续传下一帧数据
//                NSRange range = NSMakeRange(indexNow*PACKET_SIZE, PACKET_SIZE);
//                [self WriteDataWithRange:range];//传range
                //如果数据初始化，需要发送第一帧数据
                NSLog(@"15 43----传送送开始数据包");
                indexStart = 0;
                indexNow = 0;
                numberOfEOT = 0;
                blkNumber = 0;//编码号
                [self WriteDateWithStart];
//                if (_alertViewShouRestart == nil)
//                {
//                    _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"111111" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
//                    _alertViewShouRestart.tag = 9116;
//                    [_alertViewShouRestart show];
//                }
            }
        }
        else if([string containsString:@"18"])
        {//CA 1818   拒绝传输，需要重新开始传。  TODO: 固件升级  需要提示用户 重启眼罩 （如果用户重启眼罩，到时候需要等5S，这边检测到C就立马发送咯。）
            NSLog(@"18----拒绝传输，字符串为：%@,indexStart=%lu,,,indexNow = %lu",string,indexStart,indexNow);
            if (_alertViewShouRestart == nil)
            {
                _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"升级故障，请重启眼罩，并从绑定界面开始重连绑定进行升级！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                _alertViewShouRestart.tag = 906;
                [_alertViewShouRestart show];
            }
            
        }
        else
        {//未知错误
//            NSLog(@"0000------其他错误，字符串为：%@",string);
            if (_alertViewShouRestart == nil)
            {
                _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"升级故障，请重启眼罩，并从绑定界面开始重连绑定进行升级！"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                _alertViewShouRestart.tag = 906;
                [_alertViewShouRestart show];
            }
        }
        return ;//退出就行
    }
    
    const uint8_t * dat = delegate.readCharacteristic.value.bytes;
    NSMutableString * mutableString = [[NSMutableString alloc] initWithCapacity:0];
    for (int i = 0; i < delegate.readCharacteristic.value.length; i++)
    {
        [mutableString appendString:[NSString stringWithFormat:@"%02x",dat[i]]];
    }
    //需要先转成string，之前demo都是判断以string的形式判断的。
    NSString * string = mutableString;
    //TODO:固件升级
    if ([string isEqualToString:@"06"] || [string isEqualToString:@"15"] || [string isEqualToString:@"18"] || [string isEqualToString:@"1818"]  || [string isEqualToString:@"181818"]  || [string isEqualToString:@"18181818"])
    {
        if (_alertViewShouRestart == nil && delegate.isCheckedUpadating)
        {
//            [self.timerCheckUpdateHardWard setFireDate:[NSDate distantFuture]];//暂停定时器
            _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"眼罩处于升级模式，请重启眼罩再继续进行升级操作！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            _alertViewShouRestart.tag = 908;
            [_alertViewShouRestart show];
        }
        return ;
    }
    else if ([string isEqualToString:@"43"] || [string isEqualToString:@"4343"] || [string isEqualToString:@"434343"] || [string isEqualToString:@"43434343"])
    {
        //如果没有升级标志，那么需要提示正在升级模式，点击确认后，进行升级。
        if (_alertViewShouRestart == nil && delegate.isCheckedUpadating)
        {
//            [self.timerCheckUpdateHardWard setFireDate:[NSDate distantFuture]];//暂停定时器
            _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"检测到眼罩处于升级模式，请进行升级操作！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            _alertViewShouRestart.tag = 908;
            [_alertViewShouRestart show];
        }
        return ;
    }
    
    //需要判断下位机拼接过来的指令的
    Byte byt1[1] = {0};
    byt1[0] = 0x00;
    NSData *OOData = [NSData dataWithBytes:&byt1 length:sizeof(byt1)];
    Byte byt2[1] = {0};
    byt2[0] = 0xAA;
    NSData *AAData = [NSData dataWithBytes:&byt2 length:sizeof(byt2)];
    Byte byt3[1] = {0};
    byt3[0] = 0xEE;
    NSData *EEData = [NSData dataWithBytes:&byt3 length:sizeof(byt3)];
    Byte byt4[1] = {0};
    byt4[0] = 0xBB;
    NSData *BBData = [NSData dataWithBytes:&byt4 length:sizeof(byt4)];
    Byte byt5[1] = {0};
    byt5[0] = 0x08;
    NSData *ooData = [NSData dataWithBytes:&byt5 length:sizeof(byt5)];
    NSInteger index = incomedate.length;

    switch (index)//标准格式的。
    {
        case 5:
        {
            [self lenthFive];//长度5
        }
            break;
        case 9:
        {
            if (data2byte[2]!=0x00) {
                [self lenthNine];//判断9位状态
            }
            break;
        }
        case 10:
        {
            if (data2byte[0] == 0xAA && data2byte[1] == 0xEE && data2byte[2] != 0x00 &&data2byte[9] == 0xAA) {
                [self lenthTen:incomedate];//判断十位
            }
            break;
        }
        case 12:
        {
            if (data2byte[2] != 0x00) {
            if ([[incomedate subdataWithRange:NSMakeRange(0, 1)]isEqualToData:AAData] &&[[incomedate subdataWithRange:NSMakeRange(1, 1)]isEqualToData:BBData] &&[[incomedate subdataWithRange:NSMakeRange(2, 1)]isEqualToData:ooData] )
            {
                const uint8_t * dat = incomedate.bytes;
                NSMutableString * mutableString = [[NSMutableString alloc] initWithCapacity:0];
                for (int i = 0; i < incomedate.length; i++)
                {
                    [mutableString appendString:[NSString stringWithFormat:@"%02x",dat[i]]];
                }
                TJJLog(@"SXW__保存序列号:%@",mutableString);
                [config setSerialNumber:[mutableString substringWithRange:NSMakeRange(6, 16)]];//保存序列号
            }
            }
        }
            break;
        case 20:
        {//心电数据 20位
            int i=0;
            for (i =0;i<incomedate.length; i++)
            {
                if (data2byte[i] != 0x00) break;
            }
            if (i==20)
            {//如果是空 00。。。00
                return ;
            }
            else
            {
                if (((data2byte[0]==0xAA && data2byte[10]==0xAA) || (data2byte[0]==0xbb && data2byte[10]==0xbb)) && !delegate.isAtHeart)
                {//bb开头的是后来修改后的空采数据，aa是正常的数据。当不在接收数据界面，这边需要关闭。
                    TJJLog(@"波形未关闭，发送关闭指令,如果统计发送20次之后，还没有关闭，就提示用户眼罩故障，需要复位眼罩。");
                    self.numberOfOFFData = self.numberOfOFFData+1;//计数器统计
                    if (self.numberOfOFFData >= NUMBER_OFF_)
                    {//如果发送了20次还没有关闭掉接收数据，那么就说明眼罩处于异常
                        if (self.markShow == 0)
                        {
                            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:ERROR_RESTART delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                            alertView.tag = 89;
                            [alertView show];
                            self.markShow = 22;//只要设置不为0就是了。
                        }
                        else
                        {//已经弹出了提示框，不用弹出了。
                        }
                    }
                    else
                    {//关闭心跳数据接收
                        NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_HEART_END];
                        [delegate.peripheral writeValue:data forCharacteristic:delegate.writeCharacteristic type:CBCharacteristicWriteWithResponse];
                        [self didSuccessState];//执行状态，已经连接成功
                    }
                    return ;
                }
            }
        }
            break;
        default:
            break;
    }
    
    //蓝牙固件版本 和  蓝牙适配器版本
    NSString * stringData = [[NSString alloc] initWithData:incomedate encoding:NSUTF8StringEncoding];
    TJJLog(@"SXW__字符串打印:%@",stringData);
   
    NSRange range = [stringData rangeOfString:@"VER"];
    if (range.length == 3)
    {
        NSArray * tempArray = [stringData componentsSeparatedByString:@"."];
        NSArray * tempArray_ = [stringData componentsSeparatedByString:@"_"];
        if (tempArray.count == 2)
        {
            if (tempArray_.count == 2)
            {
                TJJLog(@"SXW__保存固件版本:%@",stringData);
                [config setHardware:stringData];//保存固件版本
                NSArray * array = [stringData componentsSeparatedByString:@"_VER"];
                NSString *Old_Version = [array lastObject];// 固件版本版本  如1.2
                CGFloat ver = [Old_Version floatValue];
                if (ver > 1.35)
                {
                    [config setMarkNewNoSendKey:YES];//设置 标记1.4 以上为YES
                }
                else
                {
                    [config setMarkNewNoSendKey:NO];//设置标记 1.4 以下的为NO
                }
                [self checkUpdateHardWare];//判断固件版本问题
            }
            else
            {//蓝牙版本号
                //需要从VER的V开始取
                NSString * stringTemp = [stringData substringFromIndex:range.location];
                TJJLog(@"SXW__蓝牙适配器版本:%@",stringTemp);
                [config setBLEHardware:stringTemp];//保存蓝牙适配器版本
            }
        }
    }
        
    
    if (delegate.judgeMonitor)
    {//脑电波开启状态
        if (delegate.isAtHeart)
        {//如果处于心电接收数据界面
            TJJLog(@"如果处于心电接收数据界面");
            if (incomedate.length == 20 &&[[incomedate subdataWithRange:NSMakeRange(0, 1)]isEqualToData:AAData] &&[[incomedate subdataWithRange:NSMakeRange(10, 1)]isEqualToData:AAData])
            {
                //在异步函数中执行
//                dispatch_queue_t queueUpdata = dispatch_queue_create("updateData", 0);
//                dispatch_sync(queueUpdata, ^{
//                    if (delegate.MonitorAry.count > 23 && delegate.isAtHeart && delegate.scope > 0)
//                    {//如果大于23个，并且处于心电界面，则通知(delegate.scope < 0标识不接受数据)
//                        NSNotification *notificationOne =[NSNotification notificationWithName:_NOTIFICATION_UPDATE_MONITOR object:nil userInfo:nil];
//                        [[NSNotificationCenter defaultCenter] postNotification:notificationOne];
////                        WaveView * vc = [WaveView sharingWaveViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-SCREEN_HEIGHT/2-5, SCREEN_HEIGHT)];
////                        vc.upDataBlock();
//                    }
//                });
                if (delegate.scope > 0)
                {
                    //解析蓝牙特征值，心电数据
                    uint8_t * b = (uint8_t *)incomedate.bytes;
                    int count = 0;
                    int temp = 0;
                    for (int i = 1; i <= 19; i++)
                    {
                        if (i == 10)
                        {
                            continue;
                        }
                        else
                        {
                            temp = (temp<<8) | (b[i]&0x0FF);
                        }
                        count++;//
                        if (count == 3)
                        {
                            count = 0;
                            int32_t point;
                            if (temp&0x800000)
                            {
                                point = (int32_t)(temp|0xFF000000);
                            }else{
                                point = (int32_t)temp;
                            }
                            temp = 0;
                            
                            if (self.tempX.count != 6)
                            {
                                self.tempX = [[NSMutableArray alloc] initWithCapacity:0];//设置临时6个数据。
                                self.tempY = [[NSMutableArray alloc] initWithCapacity:0];//处理好的对比数据，设置为6个0
                                for (int i=0;i<6;i++)
                                {
                                    [self.tempX addObject:@(0)];//添加6个0
                                    [self.tempY addObject:@(0)];//添加6个0
                                }
                            }
                            
                            
                            if (delegate.scope > 15000)//心电频率20000，脑电2500
                            {//心电过滤后添加  在异步函数中执行
                                dispatch_queue_t queue = dispatch_queue_create("company", 0);
                                dispatch_sync(queue, ^{
                                    [delegate.MonitorAry addObject:[self overfiltering:@(point)]];
                                });
                            }
                            else if(delegate.scope > 9000)
                            {//如果是肌电  肌电频率为10000，不处理，这边直接添加点
                                [delegate.MonitorAry addObject:@(point)];
                            }
                            else if (delegate.scope > 2000)
                            {//脑电2500
                                [delegate.MonitorAry addObject:@(point)];
                            }
                            else
                            {//其他 心率值小于0的，这边小于0的，不需要处理。
                            }
                        }
                        else
                        {//count < 3 (1,2bit的时候，不需要处理，3个字节表示一个数据点)
                        }
                    }
                }
                else
                {//心率值小于0的，这边剔除掉，不需要处理
                }
            }
            else
            {//不做处理
            }
        }
        else
        {//如果
            TJJLog(@"关闭请求心跳数据请求");
            //发送关闭接收脑电数据指令，没有处于心电界面，因为退出了。
            if (delegate.peripheral != nil)
            {
                NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_HEART_END];
                [delegate.peripheral writeValue:data forCharacteristic:delegate.writeCharacteristic type:CBCharacteristicWriteWithResponse];
            }
            [delegate.MonitorAry removeAllObjects];//清空数据
            delegate.judgeMonitor = NO;//实时检测 模式关闭
        }
    }
    else
    {//脑电波检测状态关闭
        if (incomedate.length == 20 &&[[incomedate subdataWithRange:NSMakeRange(0, 1)]isEqualToData:AAData] &&[[incomedate subdataWithRange:NSMakeRange(10, 1)]isEqualToData:AAData])
        {//发送关闭接收脑电数据指令
            TJJLog(@"SXW_____需要关闭请求");
            if (delegate.peripheral != nil)
            {
                TJJLog(@"SXW_____需要关闭请求222");
                NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_HEART_END];
                [delegate.peripheral writeValue:data forCharacteristic:delegate.writeCharacteristic type:CBCharacteristicWriteWithResponse];
            }
            [delegate.MonitorAry removeAllObjects];//清空数据
            delegate.judgeMonitor = NO;//实时检测 模式关闭
        }
        else if (self.report) //睡眠报告大于一条数据
        {
            TJJLog(@"不是一条报告------------------%@",self.reportData);
            for (int i =0; i<incomedate.length; i++)
            {
                if (![AAData isEqualToData:[incomedate subdataWithRange:NSMakeRange(i, 1)]])
                {
                    if ([OOData isEqualToData:[incomedate subdataWithRange:NSMakeRange(i, 1)]])
                    {
                        continue;
                    }
                    else
                    {
                        [self.reportData appendData:[incomedate subdataWithRange:NSMakeRange(i, 1)]];//追加报告
                    }
                }
                else
                {
                    self.report = NO;
                    TJJLog(@"报告数组整条报告%@",self.reportData);
                    //判断报告长度
                    if (delegate.sleepReporeLenth == self.reportData.length)
                    {
                        delegate.judgeSleepReportLenth = YES;
                    }
                    
                    [config setSleep:self.reportData];//保存睡眠报告到UserConfig（原来的）
                    [config setDreamImproveShow:[config isDreamImprove]];//将标记赋值给显示标记
                    [config setSleepImproveShow:[config isSleepImprove]];//将标记赋值给显示标记
                    //data 转char
                    char *test = (char *)[self.reportData bytes];
                    NSInteger leng = self.reportData.length;
                    [config setSLeepTime:[NSString stringWithFormat:@"%d",(int)leng]];//SXW__保存睡眠时间
                    TJJLog(@"大于1条睡眠数据计算");
                    NSString * endTime = [TJJDefines getReportEndTime];
                    [config setSleepEndTime:endTime];//根据睡眠报告长度设置结束时间
                    [config setHadSetEndTime:YES];//设置时间标志

                    TJJLog(@"shuimian长度时间：%@",endTime);

                    [self setLocalSleepAndDeepAndDreamTime];//更新首页睡眠时间展示
                    assessment(test,(int)self.reportData.length);
                    
                    //测试数据
//                    NSString  * string = STRINGTEST;
//                    NSData * dataTemp = [string dataUsingEncoding:NSUTF8StringEncoding];
//                    
//                    [userConfig setSleep:dataTemp];//SXW__保存睡眠报告到UserConfig
//                    //data 转char
//                    char *test = (char *)[dataTemp bytes];
//                    NSInteger leng = dataTemp.length;
//                    [userConfig setSLeepTime:[NSString stringWithFormat:@"%lu",leng]];//TODO：SXW__保存睡眠时间
//                    [self setLocalSleepAndDeepAndDreamTime];
//                    TJJLog(@"大于1条睡眠数据计算");
//                    assessment(test,(int)dataTemp.length);
                    
                }
            }
        }
        
        //睡眠报告数据
        if (
            (incomedate.length >= 6
             &&
             incomedate.length <= 18
             &&
             [[incomedate subdataWithRange:NSMakeRange(0, 1)]isEqualToData:AAData]
             &&
             [[incomedate subdataWithRange:NSMakeRange(1, 1)]isEqualToData:EEData]
             &&
             [[incomedate subdataWithRange:NSMakeRange(2, 1)]isEqualToData:OOData])
            ||
            (incomedate.length > 18
             &&
             [[incomedate subdataWithRange:NSMakeRange(0, 1)]isEqualToData:AAData]
             &&
             [[incomedate subdataWithRange:NSMakeRange(1, 1)]isEqualToData:EEData])
            )
        {
            TJJLog(@"报告进来了！！！！！！！！");
            [self lenthEighteen:incomedate];
        }
    }
}

#pragma mark -
#pragma mark 电量请求指令
- (void)homeWritePower
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_POWER];
    if (delegate.writeCharacteristic!=nil &&[ delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [delegate.peripheral writeValue:data
                      forCharacteristic:delegate.writeCharacteristic
                                   type:CBCharacteristicWriteWithResponse];
    }
    TJJLog(@"电量写入");
}

#pragma mark -
#pragma mark 读取硬件版本信息指令
- (void)readHardInfo
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_READER_VERSION];
    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [delegate.peripheral writeValue:data
                      forCharacteristic:delegate.writeCharacteristic
                                   type:CBCharacteristicWriteWithResponse];
    }
    TJJLog(@"硬件版本请求");
}

#pragma mark -
#pragma mark 读取蓝牙适配器版本信息指令
- (void)readBLEHardInfo
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_READER_BLEVERSION];
    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [delegate.peripheral writeValue:data
                      forCharacteristic:delegate.writeCharacteristic
                                   type:CBCharacteristicWriteWithResponse];
    }
    TJJLog(@"蓝牙适配器版本请求");
}

#pragma mark -
#pragma mark 读取硬件序列号信息指令
- (void)readSerialNumber
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_READER_SERIALNUMBER];
    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [delegate.peripheral writeValue:data
                      forCharacteristic:delegate.writeCharacteristic
                                   type:CBCharacteristicWriteWithResponse];
    }
    TJJLog(@"序列号请求");
}

#pragma mark -
#pragma mark 配对成功之后执行的状态请求
- (void)didSuccessState
{
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    delegate.Bluetooth = YES;//蓝牙绑定成功
    TJJLog(@"成功状态修改");
    [self performSelector:@selector(currentPowerHome) withObject:nil];//请求电量状态
    //电量图标，需要在获取具体电量之后进行改变。
    [self.redUser stopAnimating];//左AppDelegate *delegate = [[UIApplication sharedApplication] delegate];上角图标停止闪烁
    self.redUser.image = [UIImage imageNamed:@"home - head"];
    //每次配对成功之后需要发送以下信息，同步时间、读取硬件版本、读取硬件序列号、读取电量。
    [writeCurrentTime setFireDate:[NSDate distantPast]];//开启定时器定时器。
    delegate.myRemoveConnect = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"readInfoOfHardWare" object:nil];//发送通知，读取硬件info
}

#pragma mark -
#pragma mark 左上角红色显示
- (void)redUserInfo:(NSNotification *)Not
{
    NSDictionary *dict=[Not userInfo];
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    
    int judgeValue = [dict[@"keyPower1"] intValue];
    NSString *head = dict[@"disConnect"];
    TJJLog(@"左上角红色显示%@",head);
    if (delegate.Bluetooth == YES)
    {
        if (judgeValue == 1) {
            [self.redUser startAnimating];//左上角提示开始闪烁
        }
        else
        {
            [self.redUser stopAnimating];//左上角图标停止闪烁
            self.redUser.image = [UIImage imageNamed:@"home - head"];//SXW__标记
        }
    }else
    {
        [self.redUser startAnimating];
    }
    if ([head isEqualToString:@"NO"]) {
        [self.redUser startAnimating];//左上角提示开始闪烁
    }
}

#pragma mark -
#pragma mark 时间同步写入
- (void)writeCurrentTimeFunc
{
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:date];
    NSInteger year = [comps year] - 2000;
    NSInteger month = [comps month];
    NSInteger week = [comps weekday];
    NSInteger day = [comps day];
    NSInteger currentHour = [comps hour];
    NSInteger minute = [comps minute];
    NSInteger second = [comps second];
    //Week: 1－星期天;2－星期一;3－星期二;4－星期三；5－星期四；6－星期五；7－星期六
    NSInteger weekDay;
    switch (week) {
        case 1:
            weekDay = 7;//之前 7  现在7
            break;
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
            weekDay = week-1;
            break;
        default:
            break;
    }
    //时间设置问题
    NSInteger myYear = (year/10)*16+year%10;
    NSInteger myMonth = (month/10)*16+month%10;
    NSInteger myDay = (day/10)*16+day%10;
    NSInteger myWeekDay = (weekDay/10)*16+weekDay%10;
    NSInteger myHour = (currentHour/10)*16+currentHour%10;
    NSInteger myMinute = (minute/10)*16+minute%10;
    NSInteger mySecond = (second/10)*16+second%10;
    AppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
    Byte byt[11] = {0};
    byt[0] = 0xAE;//ae0830 同步时间的。
    byt[1] = 0x08;
    byt[2] = 0x30;
    byt[3] = myYear;
    byt[4] = myMonth;
    byt[5] = myDay;
    byt[6] = myWeekDay;
    byt[7] = myHour;
    byt[8] = myMinute;
    byt[9] = mySecond;
    byt[10] = 0xAA;
    NSData *myData = [NSData dataWithBytes:&byt length:sizeof(byt)];
    
    if ([appdelegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [appdelegate.peripheral writeValue:myData
                         forCharacteristic:appdelegate.writeCharacteristic
                                      type:CBCharacteristicWriteWithResponse];
    }
}

#pragma mark -
#pragma mark 判断报告
-(void)lenthEighteen:(NSData *)data
{
    //睡眠报告接收标记
    TJJLog(@"判断报告data----------------%@",data);
    self.report = YES;
    Byte byt1[1] = {0};
    byt1[0] = 0x00;
    NSData *OOData = [NSData dataWithBytes:&byt1 length:sizeof(byt1)];
    Byte byt2[1] = {0};
    byt2[0] = 0xAA;
    NSData *AAData = [NSData dataWithBytes:&byt2 length:sizeof(byt2)];
    //清空临时数组
    [self.reportData setLength:0];
    //16进制转10进制
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSData *three = [data subdataWithRange:NSMakeRange(3, 1)];
    uint8_t *threeLenth = (uint8_t *)three.bytes;
    NSData *two = [data subdataWithRange:NSMakeRange(2, 1)];
    uint8_t *twoLenth = (uint8_t  *)two.bytes;
    int a = threeLenth[0]&0xff;
    int b = twoLenth[0]&0xff;
    delegate.sleepReporeLenth = a+b*256;
    TJJLog(@"截取的长度%d",delegate.sleepReporeLenth);
    //除去帧头，开始存入
    for (int i = 4; i< data.length; i++)
    {
        if (![AAData isEqualToData:[data subdataWithRange:NSMakeRange(i, 1)]])
        {
            if ([OOData isEqualToData:[data subdataWithRange:NSMakeRange(i, 1)]])
            {
                continue;
            }
            else
            {
                [self.reportData appendData:[data subdataWithRange:NSMakeRange(i, 1)]];
            }
//            
//            for (int i = 0; i < reportStr.length; i ++)
//            {
//                int eee = [[reportStr substringWithRange:NSMakeRange(i, 1)] intValue];
//                int a = (eee/10)*16+eee%10;
//                Byte byt1[1] = {0};
//                byt1[0] = a;
//                NSData *data = [NSData dataWithBytes:&byt1 length:sizeof(byt1)];
//                [myReportData appendData:data];
//            }
            
        }
        //只有一条报告
        else
        {
            //报告接收关闭
            self.report = NO;
            //存入报告
            TJJLog(@"lenthEighteen::::报告数组一条报告%@",self.reportData);
            if (self.reportData.length == delegate.sleepReporeLenth) {
                delegate.judgeSleepReportLenth = YES;
            }
            //临时存储
            UserConfig *userConfig = [UserConfig sharingUserConfig];
            [userConfig setSleep:self.reportData];  //SXW__保存睡眠报告到UserConfig
            [userConfig setDreamImproveShow:[userConfig isDreamImprove]];//将标记赋值给显示标记
            [userConfig setSleepImproveShow:[userConfig isSleepImprove]];//将标记赋值给显示标记
            //data 转char
            char *test = (char *)[self.reportData bytes];
            TJJLog(@"%s%lu",test,strlen(test));
            NSInteger leng = self.reportData.length;
            [userConfig setSLeepTime:[NSString stringWithFormat:@"%d",(int)leng]];//TODO：SXW__保存睡眠时间
            UserConfig * config = [UserConfig sharingUserConfig];
            NSString * endTime = [TJJDefines getReportEndTime];
            [config setSleepEndTime:endTime];//根据睡眠报告长度设置结束时间
            [config setHadSetEndTime:YES];
            TJJLog(@"shuimian长度时间：%@",endTime);
            
            [self setLocalSleepAndDeepAndDreamTime];
            TJJLog(@"1条睡眠数据计算");
            assessment(test,(int)self.reportData.length);
        }
    }
}

#pragma mark -
#pragma mark 判断10位长度
-(void)lenthTen:(NSData *)dataa
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSMutableDictionary  *dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    //返回判断截取一个字节，判断配对成功
    NSData *data2 = [dataa subdataWithRange:NSMakeRange(8,1)];
    Byte byt[1] = {0};
    byt[0] = 0x41;//充电状态
    NSData *data = [NSData dataWithBytes:&byt length:sizeof(byt)];
    Byte byt1[1] = {0};
    byt1[0] = 0x42;
    NSData *data1 = [NSData dataWithBytes:&byt1 length:sizeof(byt1)];//充电完成
    //aaee0106aa aaee0141aa  充电的时候，发送key会返回这条指令。
    
    if ([data2 isEqualToData:data])
    {
        TJJLog(@"充电状态 6");
        //充电中
        [dict setObject:@"6" forKey:@"keyCharge"];
        [self.redUser stopAnimating];//左上角图标停止闪烁
        self.redUser.image = [UIImage imageNamed:@"home - head"];
        
        if (!delegate.Bluetooth)
        {
            delegate.Bluetooth = YES;
            [writeCurrentTime setFireDate:[NSDate distantPast]];//开启定时器定时器。
            delegate.myRemoveConnect = NO;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
            [self performSelector:@selector(writeGetCoolHome) withObject:nil afterDelay:1];//写入状态
            [self didSuccessState];//成功状态
        }
    }
    if ([data2 isEqualToData:data1])
    {
        //充电完成
        TJJLog(@"充电完成状态 7");
        [writeCurrentTime setFireDate:[NSDate distantPast]];//开启定时器定时器。
        [dict setObject:@"7" forKey:@"keyComplete"];
        [self.redUser stopAnimating];//左上角图标停止闪烁
        self.redUser.image = [UIImage imageNamed:@"home - head"];
        delegate.Bluetooth  = YES;
        delegate.myRemoveConnect = NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
        [self performSelector:@selector(writeGetCoolHome) withObject:nil afterDelay:1];
    }
}

#pragma mark -
#pragma mark 判断9位长度状态
-(void)lenthNine
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    UserConfig * config = [UserConfig sharingUserConfig];
    //返回判断截取一个字节
    //判断是否配对成功
    NSData *data1 = [delegate.readCharacteristic.value subdataWithRange:NSMakeRange(3,1)];
    
    Byte byt[1] = {0};
    byt[0] = 0x12;
    NSData *data2 = [NSData dataWithBytes:&byt length:sizeof(byt)];
    //睡眠状态
    if ([data1 isEqualToData:data2])
    {
        delegate.sleepModel = YES;
        TJJLog(@"睡眠状态开启");
        //TODO:如果从杀死应用之后，进入的。这边走这里，虽然睡眠状态已经开启，但是还是显示开启睡眠的按钮。
        if (self.sleepBtn.hidden==NO)
        {
//            NSString * startString = [config getSleepStartTime];
            [self stopWatchInterface];
        }
    }else
    {
        TJJLog(@"睡眠状态关闭");
        delegate.sleepModel = NO;
    }
    
    NSData *autoCool = [delegate.readCharacteristic.value subdataWithRange:NSMakeRange(5,1)];
    Byte byt1[1] = {0};
    byt1[0] = 0x14;
    NSData *data3 = [NSData dataWithBytes:&byt1 length:sizeof(byt1)];
    //智能唤醒
    if ([autoCool isEqualToData:data3])
    {
        delegate.sleepAutoMark = YES;
        TJJLog(@"智能唤醒重复开启");
    }
    else
    {
        delegate.sleepAutoMark = NO;
        TJJLog(@"智能唤醒重复关闭");
    }
    NSData *dreamCool = [delegate.readCharacteristic.value subdataWithRange:NSMakeRange(6,1)];
    Byte byt2[1] = {0};
    byt2[0] = 0x15;
    NSData *data4 = [NSData dataWithBytes:&byt2 length:sizeof(byt2)];
    //梦境控制状态
    if ([dreamCool isEqualToData:data4])
    {
        delegate.dreamImprove = YES;
        [config setDreamImprove:YES];
        TJJLog(@"梦境控制状态开启");
    }
    else
    {
        delegate.dreamImprove = NO;
        [config setDreamImprove:NO];
        TJJLog(@"梦境控制状态关闭");
    }
    NSData *sleepCool = [delegate.readCharacteristic.value subdataWithRange:NSMakeRange(7,1)];
    Byte byt3[1] = {0};
    byt3[0] = 0x16;
    NSData *data5 = [NSData dataWithBytes:&byt3 length:sizeof(byt3)];
    //睡眠改善状态
    if ([sleepCool isEqualToData:data5])
    {
        TJJLog(@"睡眠改善状态开启");
        delegate.sleepImprove = YES;
        [config setSleepImprove:YES];
    }else
    {
        TJJLog(@"睡眠改善状态关闭");
        delegate.sleepImprove = NO;
        [config setSleepImprove:NO];
    }
}

#pragma mark -
#pragma mark 长度5判断
-(void)lenthFive
{//这里判断的都是外部设备返回过来的信息，所以，这边肯定知道设备已经返回数据了。可以隐藏提示了。
    [connectingAlert dismissWithClickedButtonIndex:0 animated:YES];//自动点击重新连接提示信息
    //全局变量
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    UserConfig *config = [UserConfig sharingUserConfig];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    //返回判断截取一个字节
    //判断是否配对成功
    NSData *data1 = [delegate.readCharacteristic.value subdataWithRange:NSMakeRange(3,1)];
    Byte byt[1] = {0};
    byt[0] = 0x06;
    NSData *data2 = [NSData dataWithBytes:&byt length:sizeof(byt)];
    if ([data1 isEqualToData:data2])
    {//配对成功
        TJJLog(@"配对成功 06");
        if (!delegate.Bluetooth)
        {
            [self didSuccessState];//执行状态
        }
    }
    Byte nokey[1] = {0};
    nokey[0] = 0x07;
    NSData *currentNoKey = [NSData dataWithBytes:&nokey length:sizeof(nokey)];
    if ([data1 isEqualToData:currentNoKey])
    {
        TJJLog(@"配对错误 07 key错误");
        [TJJ_SD_BLE_INSTRUCTIONS unBind:@"key"];
        TJJALERT_VIEW(@"眼罩绑定失效，请重新进行设备绑定！");
    }
    //电池电量返回状态1
    Byte byt1[1] = {0};
    byt1[0] = 0x21;
    NSData *data3 = [NSData dataWithBytes:&byt1 length:sizeof(byt1)];
    if ([data1 isEqualToData:data3]) {
        [dict setObject:@"1" forKey:@"keyPower1"];
        TJJLog(@"电量1");
        [self startActionNewsPower];//设置左上角黄色显示小图标
        [self.redUser startAnimating];//左上角提示开始闪烁
        //发送电量改变的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
    }
    //电池电量返回状态2
    Byte byt2[1] = {0};
    byt2[0] = 0x22;
    NSData *data4 = [NSData dataWithBytes:&byt2 length:sizeof(byt2)];
    if ([data1 isEqualToData:data4]) {
        [self startActionNews];//设置左上角黄色显示小图标
        [self.redUser stopAnimating];//左上角提示停止闪烁
        self.redUser.image = [UIImage imageNamed:@"home - head"];//设置提示图标有白色头像
        [dict setObject:@"2" forKey:@"keyPower2"];
        TJJLog(@"电量2");
        //发送电量改变的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
    }
    //电池电量返回状态3
    Byte byt3[1] = {0};
    byt3[0] = 0x23;
    NSData *data5 = [NSData dataWithBytes:&byt3 length:sizeof(byt3)];
    if ([data1 isEqualToData:data5]) {
        [self startActionNews];//设置左上角黄色显示小图标
        [self.redUser stopAnimating];//左上角提示停止闪烁
        self.redUser.image = [UIImage imageNamed:@"home - head"];//设置提示图标有白色头像
        [dict setObject:@"3" forKey:@"keyPower3"];
        TJJLog(@"电量3");
        //发送电量改变的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
    }
    //电池电量返回状态4
    Byte byt4[1] = {0};
    byt4[0] = 0x24;
    NSData *data6 = [NSData dataWithBytes:&byt4 length:sizeof(byt4)];
    if ([data1 isEqualToData:data6]) {
        [self startActionNews];//设置左上角黄色显示小图标
        [self.redUser stopAnimating];//左上角提示停止闪烁
        self.redUser.image = [UIImage imageNamed:@"home - head"];//设置提示图标有白色头像
        [dict setObject:@"4" forKey:@"keyPower4"];
        TJJLog(@"电量4");
        //发送电量改变的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
    }
    //电池电量返回状态5
    Byte byt5[1] = {0};
    byt5[0] = 0x25;
    NSData *data7 = [NSData dataWithBytes:&byt5 length:sizeof(byt5)];
    if ([data1 isEqualToData:data7]) {
        [self startActionNews];//设置左上角黄色显示小图标
        [self.redUser stopAnimating];//左上角提示停止闪烁
        self.redUser.image = [UIImage imageNamed:@"home - head"];//设置提示图标有白色头像
        [dict setObject:@"5" forKey:@"keyPower5"];
        TJJLog(@"电量5");
        //发送电量改变的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
    }
    //电池电量返回状态6
    Byte byt6[1] = {0};
    byt6[0] = 0x41;
    NSData *data8 = [NSData dataWithBytes:&byt6 length:sizeof(byt6)];
    if ([data1 isEqualToData:data8]) {
        [self startActionNews];//设置左上角黄色显示小图标
        [self.redUser stopAnimating];//左上角提示停止闪烁
        self.redUser.image = [UIImage imageNamed:@"home - head"];//设置提示图标有白色头像
        [dict setObject:@"6" forKey:@"keyCharge"];
        TJJLog(@"正在充电6");
        //发送电量改变的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
    }
    //电池电量返回状态7
    Byte byt7[1] = {0};
    byt7[0] = 0x42;
    NSData *data9 = [NSData dataWithBytes:&byt7 length:sizeof(byt7)];
    if ([data1 isEqualToData:data9]) {
        [self startActionNews];//设置左上角黄色显示小图标
        [self.redUser stopAnimating];//左上角提示停止闪烁
        self.redUser.image = [UIImage imageNamed:@"home - head"];//设置提示图标有白色头像
        [dict setObject:@"7" forKey:@"keyComplete"];
        TJJLog(@"充电完成7");
        //发送电量改变的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
    }
    //电池正在充电判断
    Byte powering[1] = {0};
    powering[0] = 0x2F;
    NSData *powerData = [NSData dataWithBytes:&powering length:sizeof(powering)];
    if ([data1 isEqualToData:powerData]) {
        [self startActionNews];//设置左上角黄色显示小图标
        [self.redUser stopAnimating];//左上角提示停止闪烁
        self.redUser.image = [UIImage imageNamed:@"home - head"];//设置提示图标有白色头像
        [dict setObject:@"6" forKey:@"keyCharge"];
        TJJLog(@"正在充电中");
        //发送电量改变的通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
    }
    //睡眠改善开
    Byte byt8[1] = {0};
    byt8[0] = 0x0C;
    NSData *data10 = [NSData dataWithBytes:&byt8 length:sizeof(byt8)];
    if ([data1 isEqualToData:data10]) {
        delegate.sleepImprove = YES;
        [config setSleepImprove:YES];//设置睡眠改善 yes
        TJJLog(@"睡眠改善开启");
    }
    //睡眠改善关
    Byte byt9[1] = {0};
    byt9[0] = 0x0D;
    NSData *data11 = [NSData dataWithBytes:&byt9 length:sizeof(byt9)];
    if ([data1 isEqualToData:data11]) {
        
        
        delegate.sleepImprove = NO;
        [config setSleepImprove:NO];//设置睡眠改善  no
        TJJLog(@"睡眠改善关闭");
    }
    //梦境控制开
    Byte byt10[1] = {0};
    byt10[0] = 0x0A;
    NSData *data12 = [NSData dataWithBytes:&byt10 length:sizeof(byt10)];
    if ([data1 isEqualToData:data12]) {
        delegate.dreamImprove = YES;
        [config setDreamImprove:YES];//设置梦境控制开启 yes
        TJJLog(@"梦境控制开启");
    }
    //梦境控制关
    Byte byt11[1] = {0};
    byt11[0] = 0x0B;
    NSData *data13 = [NSData dataWithBytes:&byt11 length:sizeof(byt11)];
    if ([data1 isEqualToData:data13]) {
        delegate.dreamImprove = NO;
        [config setDreamImprove:NO];
        TJJLog(@"梦境控制关闭");
    }
    //睡眠模式开
    Byte byt12[1] = {0};
    byt12[0] = 0x30;
    NSData *data14 = [NSData dataWithBytes:&byt12 length:sizeof(byt12)];
    if ([data1 isEqualToData:data14])
    {
        delegate.sleepModel = YES;//标记睡眠模式开启
        //TODO：如果是睡眠状态，那么需要进行相应的操作，比如。
        TJJLog(@"睡眠模式开启");
    }
    //睡眠模式关
    Byte byt13[1] = {0};
    byt13[0] = 0x31;
    NSData *data15 = [NSData dataWithBytes:&byt13 length:sizeof(byt13)];
    if ([data1 isEqualToData:data15])
    {
        delegate.sleepModel = NO;//标记睡眠模式关闭
        if (delegate.judgeSleepReportLenth == NO)
        {//报告接收不完整   睡眠长度报告不完整
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"报告接收不完整" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            if ( YES != delegate.judgeReport)
            {//没有报告判断
                [alert show];
            }
            [self stopWatchToScorollOrNep];//关闭睡眠计时
            [endAlert dismissWithClickedButtonIndex:0 animated:YES];
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(judgeOffSleepModel) object:nil];//可以取消成功
        }
        else
        {//报告网站
            [self stopWatchToScorollOrNep];//关闭睡眠计时
            [endAlert dismissWithClickedButtonIndex:0 animated:YES];
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(judgeOffSleepModel) object:nil];//可以取消成功
        }
        AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
        UserConfig *config = [UserConfig sharingUserConfig];
        [config setStopwatchTime:@"0"];
        [config setAutoXiaoQiTime:@(0)];
        delegate.xiaoqiTime = @(0);
        if (self.alarmtriggered)//闹钟有没有响
            [config setTodayAlarmClockCarryOutMark:@"1"];
        TJJLog(@"睡眠模式关闭成功");
    }
    //开启智能唤醒(1)
    Byte auto1[1] = {0};
    auto1[0] = 0x56;
    NSData *data16 = [NSData dataWithBytes:&auto1 length:sizeof(auto1)];
    if ([data1 isEqualToData:data16]) {
        delegate.sleepAutoMark = YES;
        TJJLog(@"开启智能唤醒1");
    }
    //关闭智能唤醒(1)
    Byte auto2[1] = {0};
    auto2[0] = 0x57;
    NSData *data17 = [NSData dataWithBytes:&auto2 length:sizeof(auto2)];
    if ([data1 isEqualToData:data17]) {
        delegate.sleepAutoMark = NO;
        TJJLog(@"关闭智能唤醒1");
    }
    //开启智能唤醒(2)
    Byte auto3[1] = {0};
    auto3[0] = 0x58;
    NSData *data18 = [NSData dataWithBytes:&auto3 length:sizeof(auto3)];
    if ([data1 isEqualToData:data18]) {
        delegate.sleepAutoMark = YES;
        TJJLog(@"开启智能唤醒2");
    }
    
    //关闭智能唤醒(2)
    Byte auto4[1] = {0};
    auto4[0] = 0x59;
    NSData *data19 = [NSData dataWithBytes:&auto4 length:sizeof(auto4)];
    if ([data1 isEqualToData:data19])
    {
        delegate.sleepAutoMark = NO;
        TJJLog(@"关闭智能唤醒2");
    }
    //时间同步成功返回YES
    Byte byt14[1] = {0};
    byt14[0] = 0x0E;
    NSData *data20 = [NSData dataWithBytes:&byt14 length:sizeof(byt14)];
    if ([data1 isEqualToData:data20]) {
        delegate.JudgeWriteCurrentTime = YES;
        [writeCurrentTime setFireDate:[NSDate distantFuture]];//暂停计时器
        TJJLog(@"时间同步成功");
    }
    //没有报告
    Byte reportNo[1] = {0};
    reportNo[0] = 0xFF;
    NSData *report = [NSData dataWithBytes:&reportNo length:sizeof(reportNo)];
    if ([data1 isEqualToData:report]) {
        [endAlert dismissWithClickedButtonIndex:0 animated:YES];
        //没有报告
        delegate.judgeReport = YES;
        TJJLog(@"返回无睡眠报告");
    }
    TJJLog(@"判断当前返回值%@",data1);
}



#pragma mark -
#pragma mark 点击 查看报告
- (IBAction)reportClick
{
    [self gotoReportView];//跳转到查看报告跳转函数
}

#pragma mark -
#pragma mark 查看报告页面跳转
- (void)gotoReportView
{
    ReportViewController *report = [[ReportViewController alloc] init];
    AppDelegate *delegate =  [[UIApplication sharedApplication] delegate];
    NSData * linshi = [[NSData alloc] init];
    UserConfig * config = [UserConfig sharingUserConfig];
    linshi = [config getSleep];//获取保存的睡眠报告
    if (delegate.judgeReport != YES)
    {
        if (nil == linshi) {
            report.reportJudge = NO;
        }
        else
        {
            report.reportJudge = YES;
            report.reprotData = [[NSMutableData alloc] initWithData:linshi];
            TJJLog(@"Home传入的DATA -----%@",linshi);
        }
    }else
    {
        report.reportJudge = NO;
    }
    [self presentViewController:report animated:YES completion:nil];
}

#pragma mark -
#pragma mark reporImageAnimation
-(void)reportImageAnimation
{
    [UIView beginAnimations:@"move" context:nil];
    [UIView setAnimationDuration:0];
    [UIView setAnimationDelegate:self];
}

#pragma mark -
#pragma mark 更新背景图片
-(void)backGroundUpdate
{
    dispatch_async(dispatch_get_main_queue(), ^{//主线程 刷新UI
        self.currentCalendar.text = [TJJDefines getDateTypeOne]; //设置首页日历日期
        self.currentWeek.text = [TJJDefines getStringWeekday];//首页--设置星期
        [self judgeBackGroundTime];
    });
}

#pragma mark -
#pragma mark 显示背景图片
- (void)judgeBackGroundTime
{
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
}

#pragma mark -
#pragma mark 判断今天有没有智能唤醒
- (void)judgeWeekTodayAuto
{
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:date];
    NSInteger week = [comps weekday];
    //Week:1 －－星期天；2－－星期一；3－－星期二；4－－星期三；5－－星期四；6－－星期五；7－－星期六
    self.weekToday = (int)week;//设置星期
}

#pragma mark -
#pragma mark 小憩时间显示
-(void)restTimeInterface
{
    [self setLocalSleepAndDeepAndDreamTime];//设置展示的时间
    self.monitorView.hidden = YES;//正在检测View 隐藏
    self.sleepView.hidden = NO;//小憩View 打开
    backShape.hidden = NO; //背景圆环 打开
    scoreButton.hidden = YES;//点击按钮 隐藏
    numLabel.hidden = YES;//内部数字Label  隐藏
    frontShape.hidden = YES; //加载圆环 隐藏
    self.typeLabel.hidden = NO; //类型标签 打开
    _typeLabel.text = @"小憩时间";
    UserConfig * config = [UserConfig sharingUserConfig];
    _respiteHourLabel.text = [config getLastHour];
    _respiteMinLabel.text = [config getLastMinute];
    _respiteSecLabel.text = [config getLastSec];
    [self.view bringSubviewToFront:self.sleepBtn];//将 开启睡眠button 移到最上面
    [self.view bringSubviewToFront:self.clendarBtn];//将 日历button 移到最上面
    self.sleepBtn.hidden = NO;//开启睡眠button 打开
    self.bottomTimeLabel.hidden = NO;//开始到结束时间label 打开
    self.bottomTimeLabel.text = [[NSString alloc] initWithFormat:@"%@-%@",[TJJDefines stringTimeDouble:[config getSleepStartTime]],[TJJDefines stringTimeDouble:[config getSleepEndTime]]];//睡眠开始时间——睡眠结束时间显示
}

#pragma mark -
#pragma mark 状态一 睡眠得分显示
-(void)scoresInterface
{
    [self setLocalSleepAndDeepAndDreamTime];//设置展示的时间
    self.scoresView.hidden = NO;//睡眠得分View  显示
    scoreButton.hidden = NO;//点击按钮 显示
    numLabel.hidden = NO;//内部数字Label 显示
    backShape.hidden = NO; //背景圆环显示
    frontShape.hidden = NO;//加载圆环显示
    self.monitorView.hidden = YES;//正在检查view 隐藏
    self.sleepView.hidden = YES;//小憩view 隐藏
    UserConfig * config = [UserConfig sharingUserConfig];
    self.bottomTimeLabel.text = [[NSString alloc] initWithFormat:@"%@-%@",[TJJDefines stringTimeDouble:[config getSleepStartTime]],[TJJDefines stringTimeDouble:[config getSleepEndTime]]];//睡眠开始时间——睡眠结束时间显示
    // 模拟下载进度
    timerr = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(upprogress) userInfo:self repeats:YES];
    _respiteHourLabel.textColor = APPCOLOUR;
    _respiteMinLabel.textColor = APPCOLOUR;
    _respiteSecLabel.textColor = APPCOLOUR;
}

#pragma mark -
#pragma mark 电量请求
-(void)currentPowerHome
{
//    [self performSelector:@selector(writeGetCoolHome) withObject:nil];//状态请求
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_POWER];
    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [delegate.peripheral writeValue:data
                      forCharacteristic:delegate.writeCharacteristic
                                   type:CBCharacteristicWriteWithResponse];
    }
    TJJLog(@"电量请求指令发送");
}

#pragma mark -
#pragma mark 请求状态写入定时器
-(void)writeGetCoolHome
{
    [self writeCool];//状态请求
    TJJLog(@"HOME状态请求指令发送");
    [self performSelector:@selector(judgeSleepOpen) withObject:nil afterDelay:1];
}

#pragma mark -
#pragma mark  判断睡眠模式是否开启
-(void)judgeSleepOpen
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    UserConfig *config = [UserConfig sharingUserConfig];
    if ([[config getStopwatchTime] intValue] != 0 )
    {
        lastTime = [[config getStopwatchTime] intValue];//[[NSDate date] timeIntervalSince1970];//开始睡眠的时间
        if (delegate.sleepModel == YES)
        {//如果睡眠模式开启成功
            [self stopWatchInterface];
        }
    }
}

#pragma mark -
#pragma mark 状态请求
- (void)writeCool
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];//获取全局
    NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_STATE];
    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"])
    {//发送指令
        [delegate.peripheral writeValue:data
                      forCharacteristic:delegate.writeCharacteristic
                                   type:CBCharacteristicWriteWithResponse];
    }
}

#pragma mark -
#pragma mark alertView协议方法实现
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag)
    {
        case 279:
        {//开启小憩睡眠模式
            switch (buttonIndex)
            {
                case 0:
                {//取消
                    ;
                }
                    break;
                case 1:
                {//开启睡眠模式
                    AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
                    NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_SLEEPSTART];
                    if ([appdelegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
                        [appdelegate.peripheral writeValue:data
                                         forCharacteristic:appdelegate.writeCharacteristic
                                                      type:CBCharacteristicWriteWithResponse];
                    }
                    startAlert = [[UIAlertView alloc] initWithTitle:nil message:@"睡眠模式启动中" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                    [startAlert show];
                    [self performSelector:@selector(napStartSleepModel) withObject:nil afterDelay:1.5];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 271:
        {//开启睡眠模式
            switch (buttonIndex)
            {
                case 0:
                {//取消
                    ;
                }
                    break;
                case 1:
                {//开启睡眠模式
                    AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
                    NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_SLEEPSTART];
                    if ([appdelegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
                        [appdelegate.peripheral writeValue:data
                                         forCharacteristic:appdelegate.writeCharacteristic
                                                      type:CBCharacteristicWriteWithResponse];
                    }
                    startAlert = [[UIAlertView alloc] initWithTitle:nil message:@"睡眠模式启动中" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                    [startAlert show];
                    [self performSelector:@selector(startSleepModelFunc) withObject:nil afterDelay:1.5];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 272:
        {//关闭睡眠模式
            switch (buttonIndex)
            {
                case 0:
                {//取消
                }
                    break;
                case 1:
                {//确定关闭睡眠模式
                    AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
                    [myTimerr setFireDate:[NSDate distantFuture]];//暂停定时器
                    NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_SLEEPEND];
                    if ([appdelegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
                        [appdelegate.peripheral writeValue:data
                                         forCharacteristic:appdelegate.writeCharacteristic
                                                      type:CBCharacteristicWriteWithResponse];
                    }
                    //8s后判断有没有写入成功
                    [self performSelector:@selector(judgeOffSleepModel) withObject:nil afterDelay:8];
                    //5S后判断有没有分数 需不需要上传报告  （上传睡眠报告接口）
                    [self performSelector:@selector(sleepTimeAndSleepReport) withObject:nil afterDelay:5];
                    endAlert = [[UIAlertView alloc] initWithTitle:nil message:@"报告接收中" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                    [endAlert show];
                    
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 97:
        {//重新登录 先清除数据
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setHaveLogin:@"lalala"];//
            [config setToken:@"123"];//token
            [config setUserHeadData:nil];
            UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
            loginVc.quit = YES;
            [self.navigationController pushViewController:loginVc animated:YES];
        }
            break;
        case 66:
        {//更新下载应用程序
            switch (buttonIndex)
            {
                case 0:
                {//取消
                }
                    break;
                case 1:
                {
                    //连接跳转  现在写死下载地址
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URL_DOWN_SOFTDOWN]];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 89:
        {//提示用户重启眼罩，结束关闭心电数据的发送
            self.numberOfOFFData = 0;//计数清零
            self.markShow = 0;//恢复标记
        }
            break;
        case 18:
        {
            //TODO:SXW___关闭睡眠模式引导
//            self.buttonTest.hidden = YES;//隐藏用户使用button
            self.maskView.hidden = YES;//隐藏 用户指导遮层
            //存储第一次使用的数据，改变标记
            UserConfig * config = [UserConfig sharingUserConfig];
            [config setFirstUseSleep:FIRSTUSESLEEP];
        }
            break;
        case 88:
        {//用户下载固件
            if (buttonIndex == 0)
            {
                //需要调用下载数据。并且显示 下载固件的样式
                [self downloadFile];//下载文件
                self.alerDown = nil;
            }
        }
            break;
        case 906:
        {//提示需要重启眼罩
            _alertViewShouRestart = nil;
            indexStart = 0;//传输数据的所有标志位清零
            indexNow = 0;
            numberOfEOT = 0;
            blkNumber = 0;//编码号
            [TJJ_SD_BLE_INSTRUCTIONS unBind:@"key"];//解除绑定操作
            //所有的标志位 清零
            UserConfig * config = [UserConfig sharingUserConfig];
            AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
            delegate.updating = NO;//标记正在升级
            delegate.isCheckedUpadating = YES;//初始化为YES
            delegate.isUpdateHardWare = NO;
            [config setUpdateHardWare:NO];
            SliderViewController * sled = [SliderViewController sharedSliderController];
            [sled openPanGesttureRec];//打开 首页滑动
            //移除图层 延迟1S
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.arrayViews.count)
                {//如果有弹出进度框
                    [self.arrayViews enumerateObjectsUsingBlock:^(SDView *demoView, NSUInteger idx, BOOL *stop) {
                        [demoView.progressView removeFromSuperview];//从self.view上移除
                        [demoView removeFromSuperview];//移除demoView 解决挡住开启睡眠模式按钮的bug。
                        [self.viewUpdateHardWare removeFromSuperview];//移除遮罩层
                        [self.labelUpdateHardWare removeFromSuperview];//移除升级提示文本信息
                        [self.arrayViews removeAllObjects];//移除数据
                        TJJALERT_VIEW(MESSAGE_REUPDATE);//提示用户进行重新绑定重试
                    }];
                }
                else
                {//如果没有弹出进度框
                    [self.viewUpdateHardWare removeFromSuperview];//移除遮罩层
                    [self.labelUpdateHardWare removeFromSuperview];//移除升级提示文本信息
                    [self.arrayViews removeAllObjects];//移除数据
                    TJJALERT_VIEW(MESSAGE_REUPDATE);//提示用户进行重新绑定重试
                }
            });
        }
            break;
        case 908:
        {//提示正在升级状态  或者 开启应用之后里面收到15 18等指令的情况。
            indexStart = 0;
            indexNow = 0;
            numberOfEOT = 0;
            blkNumber = 0;//编码号
            TJJLog(@"提示正在升级状态按钮点击");
//            AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
//            delegate.updating = YES;//标记正在升级
            [self checkUpdateHardWare];//直接跳转到检查固件更新界面
            _alertViewShouRestart = nil;
            //切换到首页 TODO:固件升级， 需要判断当前是否处于实时显示界面。
            NSLog(@"woc %@",self.navigationController.viewControllers);
            SliderViewController * slider = [SliderViewController sharedSliderController];
            [self.navigationController popToRootViewControllerAnimated:NO];
            [slider closeSideBar];//关闭侧边栏
        }
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark 获取更新版本信息 Session 下载
- (void)getUpdateVersionDownLoad
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
    NSString *urlString = URL_DOWN_SOFT_UPDATE;//设置下载路径
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        // 指定下载文件保存的路径
        //        NSLog(@"%@ %@", targetPath, response.suggestedFilename);
        // 将下载文件保存在缓存路径中
        NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];
        // URLWithString返回的是网络的URL,如果使用本地URL,需要注意
        NSURL *fileURL1 = [NSURL URLWithString:path];
        NSURL *fileURL = [NSURL fileURLWithPath:path];
        NSLog(@"== %@ |||| %@", fileURL1, fileURL);
        return fileURL;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"下载完进行操作：%@ %@", filePath, error);
        NSString * softVersionString = [NSString stringWithContentsOfURL:filePath encoding:NSUTF8StringEncoding error:nil];
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];// app版本
        TJJLog(@"iOS版本txt文档，下载操作成功，网络版本：%@--当前版本：%@",softVersionString,app_Version);
        //删除本地存储的txt文本文件
        NSFileManager * defaultManager = [NSFileManager defaultManager];
        [defaultManager removeItemAtURL:filePath error:nil];
        //判断应用版本是否有新版本  版本号比较
        if ([softVersionString compare:app_Version options:NSNumericSearch] == NSOrderedDescending)
        {//softVersionString 版本高
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setSoftwareURL:URL_DOWN_SOFTDOWN];
            UIAlertView * aler = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"发现最新版本，是否升级？" delegate:self cancelButtonTitle:@"下次更新" otherButtonTitles:@"立马更新", nil];
            aler.tag = 66;
            [aler show];
        }
        else
        {//app_Version 版本高 （老版本高，不处理）
        }
    }];
    [task resume];
}

#pragma mark -
#pragma mark 过滤波方法心电
- (NSNumber *)overfiltering:(NSNumber *)number
{//接收一个源数据，返回一个过滤之后的过滤波数据
    [self.tempX addObject:number];//添加一个新数据
    [self.tempX removeObjectAtIndex:0];//移除第一个数据
    NSInteger n = self.tempX.count-1;//n的坐标。
    double newNumber = ([self.tempY[n-1] doubleValue] +0.2925*([self.tempX[n] doubleValue]-[self.tempX[n-5] doubleValue]))/1.25;//newpt = (y.get(n-1)+0.2925*(x.get(n)-x.get(n-5)))/1.25
    [self.tempY addObject:@(newNumber)];
    [self.tempY removeObjectsInRange:NSMakeRange(0, 1)];
    return @(newNumber);//返回NSNumber类型的数据
}

#pragma mark -
#pragma mark 创建悬浮的返回按钮
- (void)createWindowBackButton
{
    self.buttonUserOrder.frame =CGRectMake(0, 0,SCREEN_WIDTH, SCREEN_HEIGHT);//设置frame
    //如果需要设置addTarget这边自己
    [self.buttonUserOrder addTarget:self action:@selector(destroaryUserOrderButton) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonUserOrder setBackgroundColor:[UIColor redColor]];
    _window = [[UIWindow alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT)];
    _window.windowLevel = UIWindowLevelAlert+1;
//    _window.backgroundColor = [UIColor clearColor];
    [_window addSubview:self.buttonUserOrder];
    [_window makeKeyAndVisible];//关键语句,显示window
}

#pragma mark -
#pragma mark 销毁用户指导关闭睡眠模式的button
- (void)destroaryUserOrderButton
{//关闭睡眠模式引导
    self.maskView.hidden = YES;//隐藏 用户指导遮层
    UserConfig * config = [UserConfig sharingUserConfig];
    [config setFirstUseSleep:FIRSTUSESLEEP];    //存储第一次使用的数据，改变标记
    [self resignWindow]; //这是关闭注销悬浮的按钮
}
#pragma mark -
#pragma mark 关闭悬浮的window
- (void)resignWindow
{
    [_window resignKeyWindow];
    _window = nil;
}
#pragma mark -
#pragma mark 本地推送按钮点击
- (IBAction)buttonPushClickAction:(id)sender {
    UIButton * button = (UIButton *)sender;
    NSInteger index = button.tag;
    UserConfig * config = [UserConfig sharingUserConfig];
    switch (index)
    {
        case 375:
        {//推送开关
            TJJLog(@"推送开关");
            [UIView animateWithDuration:0.3 animations:^{
                self.view_push.hidden = !self.view_push.hidden;
                if (!self.view_push.hidden)
                {//如果改变之后是打开的
                    [self.view bringSubviewToFront:self.view_push];//将self.view_push 放在最上层
                    self.view_push.layer.cornerRadius = 8.0;//切圆角
                    self.view_push.layer.masksToBounds = YES;
                    
                    if (backShape.hidden)
                    {//背景圆环的状态保留
                        [config setbackShapeHidden:YES];
                    }
                    else
                    {
                        [config setbackShapeHidden:NO];
                        backShape.hidden = YES;//隐藏
                    }
                    
                    if (frontShape.hidden)
                    {//加载圆环的状态保留
                        [config setfrontShapeHidden:YES];
                    }
                    else
                    {
                        [config setfrontShapeHidden:NO];
                        frontShape.hidden = YES;//隐藏
                        numLabel.hidden = YES;//加载的分数也隐藏
                    }
                    
                    if (self.sleepBtn.hidden)
                    {//睡眠按钮的状态保留
                        [config setsleepBthHidden:YES];
                    }
                    else
                    {
                        [config setsleepBthHidden:NO];
                        self.sleepBtn.hidden = YES;//隐藏
                    }
                    
                    if (scoreButton.hidden)
                    {//小憩睡眠按钮的状态保留
                        [config setScoreButtonHidden:YES];
                    }
                    else
                    {
                        [config setScoreButtonHidden:NO];
                        scoreButton.hidden = YES;//隐藏
                    }
                    
                    if (self.monitorBtn.hidden)
                    {//关闭睡眠报告按钮的状态保留
                        [config setmonitorBthHidden:YES];
                    }
                    else
                    {
                        [config setmonitorBthHidden:NO];
                        self.monitorBtn.hidden = YES;//隐藏
                    }
                    
                    NSString * tempUrlString = [config getImageURL];//获取背景图片地址
                    //设置本地推送背景图片，网络下载。
                    [self.button_goWeb setBackgroundImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: tempUrlString]]] forState:UIControlStateNormal];
                }else
                {//恢复圆环的状态
                    if (![config getbackShapeHidden])
                    {
                        backShape.hidden = NO;
                    }
                    if (![config getfrontShapeHidden])
                    {
                        frontShape.hidden = NO;
                        numLabel.hidden = NO;//加载的分数也显示
                    }
                    //恢复按钮的状态
                    if (![config getsleepBthHidden])
                    {//睡眠按钮的状态
                         self.sleepBtn.hidden = NO;
                    }
                    
                    if (![config getScoreButtonHidden])
                    {//小憩睡眠按钮的状态
                        scoreButton.hidden = NO;
                    }
                    
                    if (![config getmonitorBthHidden])
                    {//关闭睡眠报告按钮的状态保留
                        self.monitorBtn.hidden = NO;
                    }
                }
            } completion:^(BOOL finished) {
                ;
            }];
        }
            break;
        case 376:
        {//推文链接
            TJJLog(@"推文链接");
            NSString * tempUrlString = [config getPushURL];
//            TJJ_LINK_URL(tempUrlString);//链接跳转
            TJJWebViewController * vc = [[TJJWebViewController alloc] init];
            vc.titleString = nil;
            vc.urlLink = tempUrlString;
            [self presentViewController:vc animated:YES completion:^{
                ;
            }];
        }
            break;
        case 377:
        {//关闭推送图片展示
            TJJLog(@"关闭推送图片展示");
            [UIView animateWithDuration:0.3 animations:^{
                self.view_push.hidden = YES;
            } completion:^(BOOL finished) {
                //恢复圆环以及按钮的状态
                if (![config getbackShapeHidden])
                {
                    backShape.hidden = NO;
                }
                if (![config getfrontShapeHidden])
                {
                    frontShape.hidden = NO;
                    numLabel.hidden = NO;//加载的分数也显示
                }
                //恢复按钮的状态
                if (![config getsleepBthHidden])
                {//睡眠按钮的状态
                    self.sleepBtn.hidden = NO;
                }
                
                if (![config getScoreButtonHidden])
                {//小憩睡眠按钮的状态
                    scoreButton.hidden = NO;
                }
                
                if (![config getmonitorBthHidden])
                {//关闭睡眠报告按钮的状态保留
                    self.monitorBtn.hidden = NO;
                }
            }];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark -
#pragma mark 固件升级  初始化固件升级等信息
- (void)configUpdateHardWard
{
    indexStart = 0;//正式开始上传数据
    indexNow = 0;
    numberOfEOT = 0;
    self.markIsEndWrite = NO;//时候传完标志，初始值是NO  暂时没使用
    PACKET_SIZE = 128;//数据包的大小。
    blkNumber = 0x00;//编号。从0x00开始
    numberAll = 0;//初始化为0，在数据加载完之后，需要再次赋值。
    [self configDataOfUpData];//初始化数据
    if (self.mutableData.length > 0)
    {
        [self changTheTypeOfAlert];//改变进度条为固件升级的样式
        //发送指令  固件升级指令
        AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
        NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_UPDATE_HARDWARE];
        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
            [delegate.peripheral writeValue:data
                          forCharacteristic:delegate.writeCharacteristic
                                       type:CBCharacteristicWriteWithResponse];
        }
        TJJLog(@"发送固件升级指令");
    }
    else
    {
        TJJLog(@"数据准备之后");
    }
    
}

#pragma mark -
#pragma mark -获取工程目录下的资源文件
- (void)configDataOfUpData
{//获取工程目录下的资源文件 只有在2分钟之后调用，并且判断条件是 绑定状态&&固件升级版本符合升级要求&&未开启升级标识
    UserConfig * config = [UserConfig sharingUserConfig];
    self.mutableData = [[NSMutableData alloc] initWithCapacity:0];
    NSString * path = [config getUpdateHardWareDownURLLocal];//获取文件本地地址
    NSData * dataOut =[NSData dataWithContentsOfFile:path options:0 error:NULL];//从FileName中读取出数据
    [self.mutableData appendData:dataOut];
    TJJLog(@"本地路径：SXW_______%@,,,,,,,data类型数据：%@",path,self.mutableData);
    ///private/var/mobile/Applications/D3384A96-753A-4372-86C1-02A712321332/tmp/update1.2.bin
    static NSInteger lengthData = 0;
    if (self.mutableData.length > 0)
    {//如果数据长度大于0，就是数据有效
        lengthData = self.mutableData.length;
        //判断数据是不是128的整数，如果不是，后面以0补齐
        if (lengthData % 128 != 0)//数据过滤
        {
            //OC语言中  不足位补0  补齐
            Byte * bytes = (Byte *)[self.mutableData bytes];
            NSInteger index = lengthData%128==0?lengthData:(lengthData/128+1)*128;
            Byte byteData[index];
            for (int i = 0; i < index; i++) {
                if (i < lengthData){
                    byteData[i] = bytes[i];
                }else{
                    byteData[i] = 0x00;//'0x1A'
                }
            }
            self.mutableData = [NSMutableData dataWithBytes:byteData length:index];
            lengthData = self.mutableData.length;
        }
        numberAll = lengthData/128;//数据包的个数。
    }
    else
    {
//        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无升级包，请先下载升级包。" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        [alertView show];
        [self downloadFile];//下载文件
    }
    
}
#pragma mark -
#pragma mark -上传Start数据包
- (void)WriteDateWithStart{
    NSLog(@"上传  Start数据包");
    //开始传数据,第一帧数据，包含文件名的数据。
    uint16_t tempCRC;
    //TODO:自己组织拼接
    NSString * stringNumber = [NSString stringWithFormat:@"%d",(int)self.mutableData.length];
    //1、先获取数据
    UserConfig * config = [UserConfig sharingUserConfig];
    NSString * tempstringOneName = [config getUpdateHardWareDownURLLocal];
    NSArray * arrayName = [tempstringOneName componentsSeparatedByString:@"/"];
//    NSString * nameStringName = [arrayName lastObject];// 获取最后一个字符串，比如update1.2.bin
    NSString * nameStringName;
    if (TESTUP == 1)
    {//如果是测试
        nameStringName = @"update1.4.bin"; //TODO:固件版本升级测试
    }
    else
    {//发布
        nameStringName = [arrayName lastObject];// 获取最后一个字符串，比如update1.2.bin
    }

    NSString * stringData = [NSString stringWithFormat:@"%@ %@",nameStringName,stringNumber];
    NSData * data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    NSInteger index = PACKET_SIZE-nameStringName.length-1-stringNumber.length;//补齐0的个数
    TJJLog(@"SXW__%@开头数据",stringData);
    Byte * bytes = (Byte *)[data bytes];
    Byte byteData[128];
    for (int i = 0; i < 128; i++) {
        if (i < 128-index){
            byteData[i] = bytes[i];
        }else{
            byteData[i] = 0x00;//'0x1A'
        }
    }
    NSData * pData = [NSMutableData dataWithBytes:byteData length:PACKET_SIZE];
    
    Byte * bytesPData = (Byte *)[pData bytes];
    //    NSLog(@"数据部分%@，字节长度：%lu",pData,pData.length);
    //头部数据
    Byte bytesHead[3];
//    bytesHead[0] = 0xFF;
    bytesHead[0] = 0x01;
    bytesHead[1] = 0x00;
    bytesHead[2] = 0xFF;
    NSData * headData = [NSMutableData dataWithBytes:bytesHead length:3];
    
    //3、获取到尾部  crc ，调用函数 //需要拼接两次。 高位：tempCRC/256  地位：tempCRC%256
    tempCRC = [self CalCRC16:bytesPData AndSize:PACKET_SIZE];
    Byte bytesFooter[2];
    bytesFooter[0] = tempCRC>>8;//高位
    bytesFooter[1] = tempCRC&0xff;//低位
    NSData * footerDataOne = [NSMutableData dataWithBytes:bytesFooter length:2];
    
    //4、拼接数据包  头+数据+尾部校验
    NSMutableData * writeData = [[NSMutableData alloc] initWithCapacity:0];
    [writeData appendData:headData];//拼接头部
    [writeData appendData:pData];//拼接数据部分
    [writeData appendData:footerDataOne];//拼接尾部
    
    //5、发送数据包，增加indexAction标记
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.updating = YES;//标记正在升级
    for (int i = 0; i < 7; i++)
    {
        static int numberI = 0;
        NSData * d;//range是前后包含的。所以下标不用减1.
        if(i < 6)
        {
            d = [writeData subdataWithRange:NSMakeRange(i*20, 20)];
        }
        else
        {
            d = [writeData subdataWithRange:NSMakeRange(i*20, 13)];
        }
        //        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        //            [delegate.peripheral writeValue:d
        //                          forCharacteristic:delegate.writeCharacteristic
        //                                       type:CBCharacteristicWriteWithResponse];
        //        }
        do
        {
            if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"])
            {
                [delegate.peripheral writeValue:d
                              forCharacteristic:delegate.writeCharacteristic
                                           type:CBCharacteristicWriteWithResponse];
                delegate.isWirteOK = NO;//标志位，指令发送
                numberI = 0;
            }
            numberI++;//自加上
            if (numberI >= 100)
            {
                if (_alertViewShouRestart == nil)
                {
                    _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"升级故障，请重启眼罩，并从绑定界面开始重连绑定进行升级！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    _alertViewShouRestart.tag = 906;
                    [_alertViewShouRestart show];
                }
            }
        }while (delegate.isWirteOK);

    }
    TJJLog(@"SXW__%@开头数据",writeData);
    [self progressSimulationUpDateHardWare:0.0];//  为0
    indexStart++;//只增加计数器
    blkNumber++;//0x00开始，依次加1.
    [NSThread sleepForTimeInterval:0.01];  //等0.01秒==10毫秒时间，没回复连下一个。

}

#pragma mark -
#pragma mark -上传第一个数据包  EOT
- (void)WriteDateWithEOT{
    NSLog(@"上传  EOT数据包");
    uint16_t tempCRC;
    //1、先获取数据  128个字节 0
    Byte byteData[128];
    for (int i = 0; i < 128; i++) {
        byteData[i] = 0x00;//'0x1A'
    }
    NSData * pData = [NSMutableData dataWithBytes:byteData length:PACKET_SIZE];
    Byte * bytesPData = (Byte *)[pData bytes];
    //    NSLog(@"数据部分%@，字节长度：%lu",pData,pData.length);
    //头部数据
    Byte bytesHead[3];
//    bytesHead[0] = 0xFF;
    bytesHead[0] = 0x04;//EOT 0x04
    bytesHead[1] = 0x00;
    bytesHead[2] = 0xFF;
    NSData * headData = [NSMutableData dataWithBytes:bytesHead length:3];
    
    //3、获取到尾部  crc ，调用函数 //需要拼接两次。 高位：tempCRC/256  地位：tempCRC%256
    tempCRC = [self CalCRC16:bytesPData AndSize:PACKET_SIZE];
    Byte bytesFooter[2];
    bytesFooter[0] = tempCRC>>8;//高位
    bytesFooter[1] = tempCRC&0xff;//低位
    NSData * footerDataOne = [NSMutableData dataWithBytes:bytesFooter length:2];
    
    //4、拼接数据包  头+数据+尾部校验
    NSMutableData * writeData = [[NSMutableData alloc] initWithCapacity:0];
    [writeData appendData:headData];//拼接头部
    [writeData appendData:pData];//拼接数据部分
    [writeData appendData:footerDataOne];//拼接尾部
    
    //5、发送数据包，增加indexAction标记
//    [self.currentPeripheral writeStringData:writeData];
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.updating = YES;//标记正在升级
    for (int i = 0; i < 7; i++) {
        static int numberI = 0;
        NSData * d;//range是前后包含的。所以下标不用减1.
        if(i < 6)
        {
            d = [writeData subdataWithRange:NSMakeRange(i*20, 20)];
        }
        else
        {
            d = [writeData subdataWithRange:NSMakeRange(i*20, 13)];
        }
//        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
//            [delegate.peripheral writeValue:d
//                          forCharacteristic:delegate.writeCharacteristic
//                                       type:CBCharacteristicWriteWithResponse];
//        }
        do
        {
            if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"])
            {
                [delegate.peripheral writeValue:d
                              forCharacteristic:delegate.writeCharacteristic
                                           type:CBCharacteristicWriteWithResponse];
                delegate.isWirteOK = NO;//标志位，指令发送
                numberI = 0;
            }
            numberI++;//自加上
            if (numberI >= 100)
            {
                if (_alertViewShouRestart == nil)
                {
                    _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"升级故障，请重启眼罩，并从绑定界面开始重连绑定进行升级！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    _alertViewShouRestart.tag = 906;
                    [_alertViewShouRestart show];
                }
            }
        }while (delegate.isWirteOK);
    }
    TJJLog(@"上传数据包 第一个 EOF");
}


#pragma mark -
#pragma mark -上传 “结束数据包”
- (void)WriteDateWithEnd{
    NSLog(@"上传  End数据包");
    uint16_t tempCRC;
    //1、先获取数据  128个字节 0
    Byte byteData[128];
    for (int i = 0; i < 128; i++) {
        byteData[i] = 0x00;//'0x1A'
    }
    NSData * pData = [NSMutableData dataWithBytes:byteData length:PACKET_SIZE];
    Byte * bytesPData = (Byte *)[pData bytes];
    //2、头部数据
    Byte bytesHead[3];
//    bytesHead[0] = 0xFF;
    bytesHead[0] = 0x01;
    bytesHead[1] = 0x00;
    bytesHead[2] = 0xFF;
    NSData * headData = [NSMutableData dataWithBytes:bytesHead length:3];
    
    //3、获取到尾部  crc ，调用函数 //需要拼接两次。 高位：tempCRC/256  地位：tempCRC%256
    tempCRC = [self CalCRC16:bytesPData AndSize:PACKET_SIZE];
    Byte bytesFooter[2];
    bytesFooter[0] = tempCRC>>8;//高位
    bytesFooter[1] = tempCRC&0xff;//低位
    NSData * footerDataOne = [NSMutableData dataWithBytes:bytesFooter length:2];
    //4、拼接数据包  头+数据+尾部校验
    NSMutableData * writeData = [[NSMutableData alloc] initWithCapacity:0];
    [writeData appendData:headData];//拼接头部
    [writeData appendData:pData];//拼接数据部分
    [writeData appendData:footerDataOne];//拼接尾部
    
    //5、发送数据包
//    [self.currentPeripheral writeStringData:writeData];
    
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    for (int i = 0; i < 7; i++)
    {
        static int numberI = 0;
        NSData * d;//range是前后包含的。所以下标不用减1.
        if(i < 6)
        {
            d = [writeData subdataWithRange:NSMakeRange(i*20, 20)];
        }
        else
        {
            d = [writeData subdataWithRange:NSMakeRange(i*20, 13)];
        }
        //        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        //            [delegate.peripheral writeValue:d
        //                          forCharacteristic:delegate.writeCharacteristic
        //                                       type:CBCharacteristicWriteWithResponse];
        //        }
        do
        {
            if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"])
            {
                [delegate.peripheral writeValue:d
                              forCharacteristic:delegate.writeCharacteristic
                                           type:CBCharacteristicWriteWithResponse];
                delegate.isWirteOK = NO;//标志位，指令发送
                numberI = 0;
            }
            numberI++;//自加上
            if (numberI >= 100)
            {
                if (_alertViewShouRestart == nil)
                {
                    _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"升级故障，请重启眼罩，并从绑定界面开始重连绑定进行升级！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    _alertViewShouRestart.tag = 906;
                    [_alertViewShouRestart show];
                }
            }
        }while (delegate.isWirteOK);
        
    }
    TJJLog(@"上传数据包 第%d个",(int)indexStart);
//    [self progressSimulationUpDateHardWare:1];//  为1
    delegate.isUpdateHardWare = NO;//设置眼罩升级的变量为NO,TODO:应该放在眼罩升级成功之后的。
    delegate.updating = NO;//标记正在更新固件
    UserConfig * config = [UserConfig sharingUserConfig];
    [config setUpdateHardWare:NO];//修改编辑变量
}

#pragma mark -
#pragma mark -上传数据包  每次传128字节
- (void)WriteDataWithRange:(NSRange)rangeNext{
    uint16_t tempCRC;//校验
    //这边需要封装数据，头+数据区+CRC
    //1、先获取数据  数据是Data类型的。
    NSData * pData = [self.mutableData subdataWithRange:rangeNext];
    Byte * bytesPData = (Byte *)[pData bytes];
    //2、获取到头部
    Byte bytesHead[3];
//    bytesHead[0] = 0xFF;
    bytesHead[0] = 0x01;//0-1 不变
    bytesHead[1] = blkNumber;
    bytesHead[2] = (~blkNumber);//2、3互逆
    
    NSData * headData = [NSMutableData dataWithBytes:bytesHead length:3];
    //3、获取到尾部  crc ，调用函数 //需要拼接两次。 高位：tempCRC/256  地位：tempCRC%256
    tempCRC = [self CalCRC16:bytesPData AndSize:PACKET_SIZE];
    Byte bytesFooter[2];
    bytesFooter[0] = tempCRC>>8;//高位
    bytesFooter[1] = tempCRC&0xff;//低位
    NSData * footerDataOne = [NSMutableData dataWithBytes:bytesFooter length:2];
    
    //4、拼接数据包  头+数据+尾部校验
    NSMutableData * writeData = [[NSMutableData alloc] initWithCapacity:0];
    [writeData appendData:headData];//拼接头部
    [writeData appendData:pData];//拼接数据部分
    [writeData appendData:footerDataOne];//拼接尾部
    
    //5、发送数据包，增加indexAction标记
//    [self.currentPeripheral writeStringData:writeData];
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.updating = YES;//标记正在升级
    for (int i = 0; i < 7; i++) {
        static int numberI = 0;
        NSData * d;//range是前后包含的。所以下标不用减1.
        if(i < 6)
        {
            d = [writeData subdataWithRange:NSMakeRange(i*20, 20)];
        }
        else
        {
            d = [writeData subdataWithRange:NSMakeRange(i*20, 13)];
        }
//        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
//            [delegate.peripheral writeValue:d
//                          forCharacteristic:delegate.writeCharacteristic
//                                       type:CBCharacteristicWriteWithResponse];
//        }
        do
        {
            if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"])
            {
                [delegate.peripheral writeValue:d
                              forCharacteristic:delegate.writeCharacteristic
                                           type:CBCharacteristicWriteWithResponse];
                delegate.isWirteOK = NO;//标志位，指令发送
                numberI = 0;
            }
            numberI++;//自加上
            if (numberI >= 100)
            {
                if (_alertViewShouRestart == nil)
                {
                    _alertViewShouRestart = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"升级故障，请重启眼罩，并从绑定界面开始重连绑定进行升级！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    _alertViewShouRestart.tag = 906;
                    [_alertViewShouRestart show];
                }
            }
        }while (delegate.isWirteOK);
    }
    TJJLog(@"上传数据包 第%d个",(int)indexStart);
    indexStart++;//执行计数器
    indexNow++;//数据包传输计数器
    blkNumber++;
    NSString * stringLength = [NSString stringWithFormat:@"%f",(indexStart*1.0-1.0)/(numberAll*1.0)];
    TJJLog(@"进度数据%d,%d,----%@",(int)indexStart,(int)numberAll,stringLength);
    [self progressSimulationUpDateHardWare:[stringLength floatValue]];//具体进度数
    //线程睡眠 500ms
//    [NSThread sleepForTimeInterval:0.5];  //等0.01秒==10毫秒时间，没回复连下一个。
}

#pragma mark -
#pragma mark -CRC
- (uint16_t)CalCRC16:(const uint8_t *)p_data AndSize:(uint32_t)size{
    uint32_t crc = 0;
    const uint8_t * dataEnd = p_data+size;
    
    while (p_data < dataEnd) {
        crc = [self UpDateCRC16:crc AndByte:*p_data++];
    }
    crc = [self UpDateCRC16:crc AndByte:0];
    crc = [self UpDateCRC16:crc AndByte:0];
    return crc&0xffffu;
}

#pragma mark -
#pragma mark -CRC16
- (uint16_t)UpDateCRC16:(uint16_t)crcIn AndByte:(uint8_t)byte{
    uint32_t crc = crcIn;
    uint32_t cin = byte|0x100;
    do{
        crc<<=1;
        cin<<=1;
        if (cin & 0x100) {
            ++crc;
        }
        if (crc & 0x10000) {
            crc ^= 0x1021;
        }
    }while(!(cin&0x10000));
    return crc&0xffffu;
}

#pragma mark -
#pragma mark -固件升级  字符串转NSData
- (NSData *)stringToData:(NSString *)string
{
    NSLog(@"发送的string：%@",string);
    int i;
    char temp[20];
    memset(temp, 0, 20);
    for (i=0;i<string.length-1;i+=2)
    {
        NSString *string2 = [string substringWithRange:NSMakeRange(i, 2)];//每两位截取
        temp[i/2]=strtoul([string2 UTF8String], 0, 16);//转换为16进制的
        
        //NSLog(@"===%d",temp[i/2]);
    }
    NSData *data = [NSData dataWithBytes:temp   length:strlen(temp)];
    return data;
}

#pragma mark -
#pragma mark -Home检查设置进入的绑定成功读取固件是否需有更新
- (void)checkUpdateHardWareHome
{
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
//    self.defaultBTServer.delegate = (id)self;
    UserConfig * config = [UserConfig sharingUserConfig];
    delegate.isCheckedUpadating = NO;//标记已经处理了，打开应用检测到正在更新状态的标志
    //获取版本
    NSURLSessionConfiguration *configURL = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configURL];
    NSString *urlString = URL_DOWN_HARDWARE_UPDATE;//设置下载路径(固件判断的txt文档)
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response){
        // 指定下载文件保存的路径
        // 将下载文件保存在缓存路径中
        NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];
        // URLWithString返回的是网络的URL,如果使用本地URL,需要注意
//        NSURL *fileURL1 = [NSURL URLWithString:path];
        NSURL *fileURL = [NSURL fileURLWithPath:path];
        return fileURL;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSString * hardWardVersionString = [NSString stringWithContentsOfURL:filePath encoding:NSUTF8StringEncoding error:nil];
        NSString * stringHardwareVersion = [config getHardware];//固件版本 本地
        if ([TJJDefines isNull:stringHardwareVersion])
        {//如果没有老版本
            [config setHardwareNumber:hardWardVersionString];//保存最新的固件版本号。
            //处理固件下载链接
            NSString * tempString = [NSString stringWithFormat:@"%@%@.bin",URL_DOWN_HARDWAREDOWN,hardWardVersionString];
            TJJLog(@"固件下载的地址：%@",tempString);
            [config setUpdateHardWareDownURL:tempString];//保存固件下载的地址
            delegate.markIsgetHardNumberHome = YES;//标记Home判断为需要升级
        }
        else
        {//如果有老版本
            NSArray * array = [stringHardwareVersion componentsSeparatedByString:@"_VER"];
            NSString *Old_Version;
//            NSString *Old_Version = [array lastObject];// 固件版本版本  如1.2
            if (TESTUP == 1)
            {//如果是测试
                Old_Version = TESTOLDHARDNMBER;//TODO:固件版本升级测试
            }
            else
            {//发布
                Old_Version = [array lastObject];// 固件版本版本  如1.2
            }
            //删除本地存储的txt文本文件
            NSFileManager * defaultManager = [NSFileManager defaultManager];
            [defaultManager removeItemAtURL:filePath error:nil];
            //判断应用版本是否有新版本  版本号比较
            if ([hardWardVersionString compare:Old_Version options:NSNumericSearch] == NSOrderedDescending)
            {//hardWardVersionString 版本高
                [config setHardwareNumber:hardWardVersionString];//保存最新的固件版本号。
                //处理固件下载链接
                NSString * tempString = [NSString stringWithFormat:@"%@%@.bin",URL_DOWN_HARDWAREDOWN,hardWardVersionString];
                TJJLog(@"固件下载的地址：%@",tempString);
                [config setUpdateHardWareDownURL:tempString];//保存固件下载的地址
                delegate.markIsgetHardNumberHome = YES;//标记Home判断为需要升级
            }
            else
            {//Old_Version 版本高 （老版本高或者相等，不处理）
                delegate.markIsgetHardNumberHome = NO;//标记Home判断为不需要升级
            }
        }
    }];
    [task resume];

}

#pragma mark -
#pragma mark -检查是否需要提示用户更新
- (void)checkUpdateHardWare
{//1、是否绑定连接  2、版本是否有更新  3、是否有更版本下载之后更新的标记 如果有，就跳过下载，直接重现发送指令
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    self.defaultBTServer.delegate = (id)self;
    UserConfig * config = [UserConfig sharingUserConfig];
    delegate.isCheckedUpadating = NO;//标记已经处理了，打开应用检测到正在更新状态的标志
    if ([[config getConnectCool] integerValue] == 1)//绑定状态  TODO:固件升级  判断条件具体用哪个
    {//如果已经绑定  之前是判断链接状态
//        delegate.Bluetooth//连接状态
//        if (![config getUpdateHardWare] && !delegate.updating && !delegate.isUpdateHardWare)
//        if (!([config getUpdateHardWare] || delegate.updating || delegate.isUpdateHardWare))
//        {//如果是未升级状态，需要判断
            //获取版本
            NSURLSessionConfiguration *configURL = [NSURLSessionConfiguration defaultSessionConfiguration];
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configURL];
            NSString *urlString = URL_DOWN_HARDWARE_UPDATE;//设置下载路径(固件判断的txt文档)
            urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url = [NSURL URLWithString:urlString];
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
            NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response){
                // 指定下载文件保存的路径
                // 将下载文件保存在缓存路径中
                NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
                NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];
                // URLWithString返回的是网络的URL,如果使用本地URL,需要注意
//                NSURL *fileURL1 = [NSURL URLWithString:path];
                NSURL *fileURL = [NSURL fileURLWithPath:path];
                return fileURL;
            } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                NSString * hardWardVersionString = [NSString stringWithContentsOfURL:filePath encoding:NSUTF8StringEncoding error:nil];
                NSString * stringHardwareVersion = [config getHardware];//固件版本 本地
                if ([TJJDefines isNull:stringHardwareVersion])
                {//如果没有老版本
                    //添加遮罩层，成功之后隐藏
                    self.viewUpdateHardWare = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
                    [self.viewUpdateHardWare setBackgroundColor:[UIColor grayColor]];
                    self.viewUpdateHardWare.alpha = 0.7;//设置透明度。
                    [self.view addSubview:self.viewUpdateHardWare];
                    delegate.updating = YES;//标记正在升级
                    //添加提醒文字。 200 480-100
                    self.labelUpdateHardWare = [[UILabel alloc] initWithFrame:CGRectMake(20, SCREEN_HEIGHT/2-100-100, SCREEN_WIDTH-40, 90)];
                    self.labelUpdateHardWare.textColor = [UIColor whiteColor];
                    self.labelUpdateHardWare.numberOfLines = 0;
                    self.labelUpdateHardWare.font = [UIFont systemFontOfSize:15];
                    self.labelUpdateHardWare.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5];
                    //        self.labelUpdateHardWare.alpha = 0.7;
//                    self.labelUpdateHardWare.text = MESSAGE_UPDATING;
                    NSMutableAttributedString* stringAlert = [[NSMutableAttributedString alloc]initWithString:MESSAGE_UPDATING];//设置平均心率
                    [stringAlert addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, MESSAGE_UPDATING.length-LENGTH_REDSTRING)];//设置前面文字白色
                    [stringAlert addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, MESSAGE_UPDATING.length-LENGTH_REDSTRING)];//设置前面文字大小
                    [stringAlert addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(MESSAGE_UPDATING.length-LENGTH_REDSTRING, LENGTH_REDSTRING)];//设置后面文字白色 bpm
                    [stringAlert addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:18] range:NSMakeRange(MESSAGE_UPDATING.length-LENGTH_REDSTRING, LENGTH_REDSTRING)];////设置前面文字大小 bpm
                    self.labelUpdateHardWare.attributedText = stringAlert;

                    [self.view addSubview:self.labelUpdateHardWare];
                    //切换到首页 TODO:固件升级， 需要判断当前是否处于实时显示界面。
                    SliderViewController * slider = [SliderViewController sharedSliderController];
                    [slider closePanGesttureRec];//禁用首页滑动
                    
                    [config setHardwareNumber:hardWardVersionString];//保存最新的固件版本号。
                    //处理固件下载链接
                    NSString * tempString = [NSString stringWithFormat:@"%@%@.bin",URL_DOWN_HARDWAREDOWN,hardWardVersionString];
                    TJJLog(@"固件下载的地址：%@",tempString);
                    [config setUpdateHardWareDownURL:tempString];//保存固件下载的地址
                    if (delegate.isUpdateHardWare)
                    {//如果是从绑定界面检测到43 或者1818进入的。
                        [self downloadFile];//下载文件
                    }
                }
                else
                {//如果有老版本
                    NSArray * array = [stringHardwareVersion componentsSeparatedByString:@"_VER"];
                    NSString *Old_Version;
//                    NSString *Old_Version = [array lastObject];// 固件版本版本  如1.2
                    if (TESTUP == 1)
                    {//如果是测试
                        Old_Version = TESTOLDHARDNMBER;//TODO:固件版本升级测试
                    }
                    else
                    {//发布
                        Old_Version = [array lastObject];// 固件版本版本  如1.2
                    }
                    //删除本地存储的txt文本文件
                    NSFileManager * defaultManager = [NSFileManager defaultManager];
                    [defaultManager removeItemAtURL:filePath error:nil];
                    //判断应用版本是否有新版本  版本号比较
                    if ([hardWardVersionString compare:Old_Version options:NSNumericSearch] == NSOrderedDescending)
                    {//hardWardVersionString 版本高
                        //添加遮罩层，成功之后隐藏
                        self.viewUpdateHardWare = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
                        [self.viewUpdateHardWare setBackgroundColor:[UIColor grayColor]];
                        self.viewUpdateHardWare.alpha = 0.7;//设置透明度。
                        [self.view addSubview:self.viewUpdateHardWare];
                        delegate.updating = YES;//标记正在升级
                        //添加提醒文字。 200 480-100
                        self.labelUpdateHardWare = [[UILabel alloc] initWithFrame:CGRectMake(20, SCREEN_HEIGHT/2-100-100, SCREEN_WIDTH-40, 90)];
                        self.labelUpdateHardWare.textColor = [UIColor whiteColor];
                        self.labelUpdateHardWare.numberOfLines = 0;
                        self.labelUpdateHardWare.font = [UIFont systemFontOfSize:15];
                        self.labelUpdateHardWare.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5];
                        //        self.labelUpdateHardWare.alpha = 0.7;
                        //                    self.labelUpdateHardWare.text = MESSAGE_UPDATING;
                        NSMutableAttributedString* stringAlert = [[NSMutableAttributedString alloc]initWithString:MESSAGE_UPDATING];//设置平均心率
                        [stringAlert addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, MESSAGE_UPDATING.length-LENGTH_REDSTRING)];//设置前面文字白色
                        [stringAlert addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, MESSAGE_UPDATING.length-LENGTH_REDSTRING)];//设置前面文字大小
                        [stringAlert addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(MESSAGE_UPDATING.length-LENGTH_REDSTRING, LENGTH_REDSTRING)];//设置后面文字白色 bpm
                        [stringAlert addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:18] range:NSMakeRange(MESSAGE_UPDATING.length-LENGTH_REDSTRING, LENGTH_REDSTRING)];////设置前面文字大小 bpm
                        self.labelUpdateHardWare.attributedText = stringAlert;
                        
                        [self.view addSubview:self.labelUpdateHardWare];
                        //切换到首页 TODO:固件升级， 需要判断当前是否处于实时显示界面。
                        SliderViewController * slider = [SliderViewController sharedSliderController];
                        [slider closePanGesttureRec];//禁用首页滑动
                        
                        [config setHardwareNumber:hardWardVersionString];//保存最新的固件版本号。

                        //处理固件下载链接
                        NSString * tempString = [NSString stringWithFormat:@"%@%@.bin",URL_DOWN_HARDWAREDOWN,hardWardVersionString];
                        TJJLog(@"固件下载的地址：%@",tempString);
                        [config setUpdateHardWareDownURL:tempString];//保存固件下载的地址
                        self.alerDown = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"发现眼罩固件升级包，请升级！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        self.alerDown.tag = 88;
                        [self.alerDown show];
                    }
                    else
                    {//Old_Version 版本高 （老版本高或者相等，不处理）
                    }
                }
            }];
            [task resume];
//        }
    }
    else
    {//如果不是处于绑定状态就不用处理
    }
    
}

#pragma mark -
#pragma mark 初始化进度条样式 固件升级
- (NSMutableArray *)arrayViews
{
    if (_arrayViews == nil) {
        _arrayViews = [NSMutableArray array];
    }
    return _arrayViews;
}

- (void)changTheTypeOfAlert
{
    [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
    SliderViewController * sled = [SliderViewController sharedSliderController];
    [sled closePanGesttureRec];//禁用首页滑动
    [self.arrayViews enumerateObjectsUsingBlock:^(SDView *demoView, NSUInteger idx, BOOL *stop) {
        [demoView.progressView removeFromSuperview];//从self.view上移除
        [demoView removeFromSuperview];//移除demoView
        [self.arrayViews removeAllObjects];//先移除 下载的进度条的样式
    }];
    [self.arrayViews addObject:[SDView ViewWithClass:[SDPieLoopProgressView class]]];//SDPieLoopProgressView  固件升级
    [self setupSubviews];// 调整示例frame
}

#pragma mark -
#pragma mark  添加progressView示例模型图
- (void)addProgressViews
{
    if (self.arrayViews.count > 0)
    {
        [self.arrayViews enumerateObjectsUsingBlock:^(SDView *demoView, NSUInteger idx, BOOL *stop) {
            [demoView.progressView removeFromSuperview];//从self.view上移除
            [demoView removeFromSuperview];//移除demoView
            [self.arrayViews removeAllObjects];//先移除 下载的进度条的样式
        }];
    }
    [self.arrayViews addObject:[SDView ViewWithClass:[SDBallProgressView class]]];//SDBallProgressView 下载
}


#pragma mark -
#pragma mark 设置progressView的frame
- (void)setupSubviews
{
    int perrowCount= 1;
    CGFloat w = 200;
    CGFloat h = w;
    CGFloat margin = (self.view.frame.size.width - perrowCount * w) / (perrowCount + 1);
    [self.arrayViews enumerateObjectsUsingBlock:^(SDView *demoView, NSUInteger idx, BOOL *stop) {
        int rowIndex = (int)idx / perrowCount;
        int columnIndex = idx % perrowCount;
        CGFloat x = margin + (w + margin) * columnIndex;
        CGFloat y = margin + (h + margin) * rowIndex;
        y = self.view.center.y-w/2;
        demoView.frame = CGRectMake(x, y, w, h);
        [self.view addSubview:demoView];
    }];
}

#pragma mark -
#pragma mark 模拟下载进度
- (void)progressSimulationDownFile:(CGFloat)lengthIndex
{
    static CGFloat progress = 0;
    progress = lengthIndex;//直接赋值就行
    if (progress >= 1.0)
    {
        NSLog(@"2222222");
        //下载固件进度条
        [self.arrayViews enumerateObjectsUsingBlock:^(SDView *demoView, NSUInteger idx, BOOL *stop) {
            demoView.progressView.progress = progress;
        }];
    }
    else
    {
        NSLog(@"11111111-----%lf",progress);
        [self.arrayViews enumerateObjectsUsingBlock:^(SDView *demoView, NSUInteger idx, BOOL *stop) {
            demoView.progressView.progress = progress;
        }];
    }
}

#pragma mark -
#pragma mark 固件更新  进度条
- (void)progressSimulationUpDateHardWare:(CGFloat)lengthIndex
{
    static CGFloat progress = 0;
    progress = lengthIndex;//直接赋值
    if (progress >= 1.0)
    {
        NSLog(@"444444");
        [self.arrayViews enumerateObjectsUsingBlock:^(SDView *demoView, NSUInteger idx, BOOL *stop) {
            demoView.progressView.progress = progress;
        }];
        //需要移除  延迟5S
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.arrayViews enumerateObjectsUsingBlock:^(SDView *demoView, NSUInteger idx, BOOL *stop) {
                [demoView.progressView removeFromSuperview];//从self.view上移除
                [demoView removeFromSuperview];//移除demoView 解决挡住开启睡眠模式按钮的bug。
                [self.viewUpdateHardWare removeFromSuperview];//移除遮罩层
                [self.labelUpdateHardWare removeFromSuperview];//移除升级提示文本信息
                [self.arrayViews removeAllObjects];//移除数据
                self.mutableData = nil;
                UserConfig * config = [UserConfig sharingUserConfig];
                [config setUpdateHardWare:NO]; //修改标记
                [TJJ_SD_BLE_INSTRUCTIONS unBind:@"key"];//解除绑定操作
                TJJALERT_VIEW(MESSAGE_RESTART);//提示用户进行重新绑定 ，清空绑定信息  TODO:固件升级
                SliderViewController * sled = [SliderViewController sharedSliderController];
                [sled openPanGesttureRec];//打开 首页滑动
            }];
        });
    }
    else
    {
        NSLog(@"333333-----%lf",progress);
        [self.arrayViews enumerateObjectsUsingBlock:^(SDView *demoView, NSUInteger idx, BOOL *stop) {
            demoView.progressView.progress = progress;
        }];
    }
}

#pragma mark -
#pragma mark 使用代理监控下载进度
- (void)downloadFile
{
    UserConfig * config = [UserConfig sharingUserConfig];
//    NSString * url = [config getUpdateHardWareDownURL];//获取网络下载固件的地址
     NSString * url;
    if (TESTUP == 1)
    {//如果是测试
        url = @"http://www.magilit.com/app_update/update1.4.bin"; //TODO:固件版本升级测试
    }
    else
    {//发布
        url = [config getUpdateHardWareDownURL];//获取网络下载固件的地址
    }
    TJJLog(@"获取网络下载固件的地址:%@",url);
    if ([url isEqualToString:@"0"])
    {//如果下载地址为空，需要重新获取下 TODO:保存固件的版本，重新拼接
        NSString * stringNumber = [config getHardwareNumber];//获取网络的版本号
        if ([stringNumber isEqualToString:@"0"])
        {//如果最新的版本号为空 需要进行网络请求，判断最新版本  获取固件版本判断的下载链接
            NSURLSessionConfiguration *configURL = [NSURLSessionConfiguration defaultSessionConfiguration];
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configURL];
            NSString *urlString = URL_DOWN_HARDWARE_UPDATE;//设置下载路径(固件判断的txt文档)
            urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url = [NSURL URLWithString:urlString];
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
            NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
                NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];
                NSURL *fileURL = [NSURL fileURLWithPath:path];
                return fileURL;
            } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                NSLog(@"下载完进行操作：%@ %@", filePath, error);
                NSString * hardWardVersionString = [NSString stringWithContentsOfURL:filePath encoding:NSUTF8StringEncoding error:nil];
                //删除本地存储的txt文本文件
                NSFileManager * defaultManager = [NSFileManager defaultManager];
                [defaultManager removeItemAtURL:filePath error:nil];
                //处理固件下载链接
                NSString * tempString = [NSString stringWithFormat:@"%@%@.bin",URL_DOWN_HARDWAREDOWN,hardWardVersionString];
                TJJLog(@"固件下载的地址：%@",tempString);
                [config setHardwareNumber:hardWardVersionString];//保存最新的固件版本号。

                [config setUpdateHardWareDownURL:tempString];//保存固件下载的地址
                [self addProgressViews];//添加下载 进度样式View
                [self setupSubviews];//调整进度 样式frame
                NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:tempString] cachePolicy:1 timeoutInterval:200];
                [[self.session downloadTaskWithRequest:request]resume];
            }];
            [task resume];
        }
        else
        {
            NSString * stringUrl = [NSString stringWithFormat:@"%@%@.bin",URL_DOWN_HARDWARE_UPDATE,stringNumber];//拼接网络下载地址
            [config setUpdateHardWareDownURL:stringUrl];//保存网络下载固件的地址
            [self addProgressViews];//添加下载 进度样式View
            [self setupSubviews];//调整进度 样式frame
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringUrl] cachePolicy:1 timeoutInterval:200];
            [[self.session downloadTaskWithRequest:request]resume];
        }
    }
    else
    {//固件下载地址是正确的
        [self addProgressViews];//添加下载 进度样式View
        [self setupSubviews];//调整进度 样式frame
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:1 timeoutInterval:200];
        [[self.session downloadTaskWithRequest:request]resume];
    }
}

#pragma mark - 代理方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
//    NSString *pathFile = [NSTemporaryDirectory() stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
//    TJJLog(@"固件下载保存的路径：%@",pathFile);
//    TJJLog(@"固件下载保存的路径：%@",pathFile);
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask,YES);//获取文件保存的路径
    NSString *ourDocumentPath =[documentPaths objectAtIndex:0];
    //    NSString *sandboxPath = NSHomeDirectory();
    //    NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"Documents"];
    NSString * itemName = URL_DOWN_HARDWAREDOWN; //文件名
    NSArray *aArray = [itemName componentsSeparatedByString:@"/"];
    NSString *filenameFirst = [aArray lastObject]; //获取到update,还需要拼接固件版本号
    UserConfig * config = [UserConfig sharingUserConfig];
    NSString *filename = [NSString stringWithFormat:@"%@%@.bin",filenameFirst,[config getHardwareNumber]]; //拼接之后是update1.2.bin
    NSString * FileName=[ourDocumentPath stringByAppendingPathComponent:filename];//fileName就是保存文件的文件名
    //保存本地文件存储的地址
    [config setUpdateHardWareDownURLLocal:FileName];
    
    NSFileManager * manger = [NSFileManager defaultManager];
    [manger copyItemAtPath:location.path toPath:FileName error:NULL];//保存文件
    TJJLog(@"文件本地保存的路径%@",FileName);
    //文件本地保存的路径/var/mobile/Applications/A704FD46-A4EB-4744-B613-17ACF03965F7/Documents/update1.2.bin

}

// 进度数据
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
    //主线程 刷新下载进度条
    NSString *strDistance=[NSString stringWithFormat:@"%2f", progress];
    NSLog(@"%lld___%lld__",totalBytesWritten,totalBytesExpectedToWrite);
    NSLog(@"进度数据：：：%f----  %@----strDistance",progress,strDistance);
    [self progressSimulationDownFile:[strDistance floatValue]];//下载进度 显示
}

// 懒加载
- (NSURLSession *)session
{
    if(_session == nil)
    {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _session;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
@end
